Before We start we would like to know about autolayout
Autolayout is a user interface builder for your application you can build the interface easily from the storyboard as you can check in the below image
By using the below procedure you can easily set leading, trailing, top, bottom, width, and height.
This blog will help you to manage these things programmatically.
1. In your view controller take an object for a text field (or which your want to use for your controller )
1 |
let myView = UITextField() |
2. Add the above object in your view controller as a subview.
1 |
self.view.addSubview(myView) |
3. Please add the below code after you added an in you view.
1 |
myView.translatesAutoresizingMaskIntoConstraints = false |
translatesAutoresizingMaskIntoConstraintsneeds to be set to false when the view will be added to a view hierarchy that is using auto layout.
4. After that you need to set a constraint for this text field you need to set four constraints for each object.
1 |
NSLayoutConstraint.init(item: myView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 100).isActive = true |
here is the explanation for each parameter
item:- for which you want to set the constraint ( for me I have set a constraint for myView which is a text field)
attribute:- what you want to set like top, bottom, leading, trailing.
relatedBy:- you can set this for constant, the constant will equal or lessthen or gratherthen.
toItem:- from where you want to set constraint
isActive:- this need to define for every time if you want to active this constraint your controller
Here you can see the all constraint for an object.
1 2 3 4 |
NSLayoutConstraint.init(item: myView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 100).isActive = true NSLayoutConstraint.init(item: myView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: -20).isActive = true NSLayoutConstraint.init(item: myView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 20).isActive = true NSLayoutConstraint.init(item: myView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50).isActive = true |
This will work the same on the landscape or portrait you can check the below images
I hope this blog helped you to implement auto-layout programmatically for any query please leave a comment to us.
For more technical blog please click here
For more information about the auto layout please click here