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
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)
])
2 Comments
Duncan C
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.Duncan C
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)