1

How do you programmatically create layout and constraints using Swift IOS. I'm familiar with storyboards, however I'm not sure how to use code to make ui elements.

1 Answer 1

2

There are three main steps. First you have to define the element, add it to the view, then add constraints.

For example,

let button = UIButton() 
button.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(button) 

NSLayoutConstraint.activate([
        button.heightAnchor.constraint(equalTo: view.heightAnchor)
      
        
])
Sign up to request clarification or add additional context in comments.

2 Comments

Note the translatesAutoresizingMaskIntoConstraints = false bit. That's important. If you forget that part, the system adds a bunch of constraints that attempt to simulate "struts and springs" auto resizing masks, which will then conflict with your AutoLayout constraints.
Also note that there at least 3 different ways to create auto layout constraints. Using layout anchors as in this answer seems the easiest way to me. (Voted)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.