UIKit Programmatic Approach: Three Different Syntax To Use UIConstraints

KD Knowledge Diet
1 min readMay 22, 2022

--

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([])

NSLayoutConstraint.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

view.constraints(equalTo: ).isActive

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

Instantiate Directly NSLayoutConstraint

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.

  1. Use nsLayoutConstarint.activate([])
  2. Use anchors
  3. Instantiate directly NSLayoutConstraint

--

--

KD Knowledge Diet
KD Knowledge Diet

Written by KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!

Responses (1)