How do I create a 1px line in Interface Builder? How do I create a 1px line in Interface Builder? ios ios

How do I create a 1px line in Interface Builder?


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.

enter image description here

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 or viewDidLoad, you are going to set the constant of the constraint to the scale of the display:

Swift

onePixelViewHeightConstraint.constant = 1/UIScreen.main.scale//enforces it to be a true 1 pixel line

Objective-C

self.onePixelViewHeightConstraint.constant = 1.f/[UIScreen mainScreen].scale;//enforces it to be a true 1 pixel line

Enjoy


I created NSLayoutConstraint subclass:

class HairlineConstraint: NSLayoutConstraint {    override func awakeFromNib() {        super.awakeFromNib()        self.constant = 1.0 / UIScreen.main.scale    }}

Then simply create your view in interface builder, add height constraint

Custom view with height constraint

and set its class to HairlineConstraint.

Set constraint class

Done.


By creating this tiny subclass of NSLayoutConstraint I'm now able to add 1px lines in IB:

@implementation NSLayoutConstraintHairline-(void)awakeFromNib{    [super awakeFromNib];    if ( self.constant == 1 ) self.constant = 1/[UIScreen mainScreen].scale;}@end

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.