Jody Heavener Jody Heavener - 6 months ago 77
Swift Question

UITextField autolayout with margins programmatically

I'm new to AutoLayout and would like to display my UITextField at 100% width with a consistent 15px left and right margin, like so:

enter image description here

Typically I would do this using CGRect, setting the width to the containing view's width minus 30px, then offset the left side by 15px:

searchTextField.frame = CGRectMake(15, 0, view.frame.width - 30, 50)


But I'd like to learn AutoLayout for this sort of thing, since it's the way to go these days. I should note that I am doing everything programmatically -- no Storyboards here.

I'd love it if someone could help me out!

Update

Wow! Thank you for all the responses. I believe all of them would achieve what I'm trying to do, but there can only be one :)

Answer

Usually I use for this cocoapod that is dealing with constraints, but if you need pure apple solution documentation states:

You have three choices when it comes to programmatically creating constraints: You can use layout anchors, you can use the NSLayoutConstraint class, or you can use the Visual Format Language.

Approach with NSLayoutConstraints in your case would be:

NSLayoutConstraint(item: textField, attribute: .Leading, relatedBy: .Equal, toItem: parentView, attribute: .LeadingMargin, multiplier: 1.0, constant: 15.0).active = true

NSLayoutConstraint(item: textField, attribute: .Trailing, relatedBy: .Equal, toItem: parentView, attribute: .TrailingMargin, multiplier: 1.0, constant: -15.0).active = true

NSLayoutConstraint(item: textField, attribute: .Top, relatedBy: .Equal, toItem: parentView, attribute: .TopMargin, multiplier: 1.0, constant: 50.0).active = true

Remember that if you don't have any constraints in the view, they would be added automatically and you'll have to deal with them and conflicts that would be created by adding new constraints on runtime. To avoid this you could either create textField manually and add it to the view or set constraints with low priority in the Interface Builder .

Comments