Note, I'm looking to make a 1px line, not a 1pt line. Meaning it should be 1px regardless of screen scale (so 0.5pt on Retina devices).
I can do this programmatically, but can I do it in the Interface Builder? For example I cannot set a UIView to have a height of less than 1.
If I can do it in IB then I don't have to declare an outlet and manually set the frame in awakeFromNib
.
Xcode 7.3 right down corner: add Height constraint in Pin.
Just in case someone else comes here wanting to know how it can be done programmatically, heres how you do it:
Interface Builder
Make a height constraint in IB to the desired view and set the constant to 1.
Then you will need to CTRL+Drag from the constraint into your custom view or ViewController.
Whenever the Xib is loaded, be it in
awakeFromNib
orviewDidLoad
, you are going to set the constant of the constraint to the scale of the display:Swift
Objective-C
Enjoy
EDIT: This answer was for @2x only devices. At that time @3x was not yet on the market!
Nowadays,
@mdvs
's answer seems to be the cleanest.Making 1px line in IB is hard even for retina-only devices. Finally I've achieved it using the
User Defined Runtime Attributes
.Here's a screenshot for setting the Height Constraint to 0.5 px (which is 1px on retina devices).
I created
NSLayoutConstraint
subclass:Then simply create your view in interface builder, add height constraint
and set its class to
HairlineConstraint
.Done.
In Swift:
By creating this tiny subclass of
NSLayoutConstraint
I'm now able to add 1px lines in IB:Any constraint with a value of 1 can be set to class
NSLayoutConstraintHairline
to make the constant effectively 1px instead of 1pt.If you ever decide to change the constant to another value, it will just work as any other constraint.