UIKit Programmatic Approach: Three Different Syntax To Use UIConstraints
Warning! This is a beginner level tutorial. But if you already had an experience with ios development, take your time if you know these by heart.
Normally, when you write UI purely with code without Storyboard, most developers use library. But if you are building a simple UILibrary, it would be a good choice not to use any third party library. And I’m pretty sure almost all ios developers know these knowledges I’m about to introduce. So acquire it!
[1] NSLayoutConstraints.activate([])
This is probably the most used API when you are writing UI with code. I think this is the simplest one to use.
[2] view.constraints(equalTo: ).isActive = true
This is the second most used API. All Swift Views have anchors. You can directly set anchors. Don’t forget to set isActive
to true when using this API.
[3] NSLayoutConstraint().isActive = true
This is not so often used, but in some cases, it can be really useful.
Conclusion
Believe or not, there are couple more ways to use NSLayoutConstraint. But these 3 ways are the easiest way to use NSLayoutConstraint.
- Use nsLayoutConstarint.activate([])
- Use anchors
- Instantiate directly NSLayoutConstraint