DeviceType & DeviceConstraint Swift 5
How to layout on different devices?💭
In this article, I’m going to describe three different ways to meet the design requirements depending on screen types.
DeviceType | DeviceConstraint | DeviceUIView + Inspectable property
While making a pixel perfect design it’s a common thing to have a different constraint, fontSize or cornerRadius depending on the device type.
DeviceType
It’s a simple Struct
of device types depending on the ScreenSize
. You can set anything while checking your device type:
It’s a good solution if you need very code check, you need a lot of changes depending on a device type or it’s just a simple check like:
if DeviceType.hasTopNotch { }
Otherwise, code might get messy 🤭. That’s why I prefer another way while working with constraints.
DeviseConstraint
It’s an IBDesignable
class with IBInspectable
variables representing constraint’s constants for each device type.
Select your constraint, set its custom class to DeviseConstraint
and add all the values you need in Attributes inspector:
There won’t be any DeviceType switch
or if else
in code anymore. That’s how it becomes clean 🧹.
DeviceUIView + Inspectable property
Imagine you don’t need both: device type checks in code and all device type values in the Attributes inspector. The only thing you need is a different fontSize
of the label while using the iPad.
In this case, I prefer to create an IPadLabel class
of UILabel
that has aniPadFontSize
inspectable variable to be able to set it in the Attributes inspector of a label. Select your label, set its custom class to IPadLabel
and add set its new property:
Along with fontSize
you can add any property you need.
SBValue
Here’s an elegant way of my friend to have a screen based value in your code.
Thanks for reading 👏
Hope you found it useful! Feel free to leave a comment, question or suggestion smth.