Auto Layout extension


  • Today we are going to see how to write an extension that will reduce amount of steps/work required to add constraints programmatically.

Common steps:

//Step 1
lblName.translatesAutoresizingMaskIntoConstraints = false
//Step 2
view.addSubview(lblName)
//Step 3
NSLayoutConstraint.activate([
lblName.centerXAnchor.constraint(equalTo: view.centerXAnchor),
lblName.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])

As you see, if you are going programatic approach instead of using storyboard, you need to add these steps of lot of objects which is PITA.

So we are going to remove boiler plate code by moving to extension of UIView.

Extension:

extension UIView {
func
addSubview(_ child:UIView,constraints:[NSLayoutConstraint]){
//Step 1
child.translatesAutoresizingMaskIntoConstraints = false
//Step2
addSubview(child)
//Step 3
NSLayoutConstraint.activate(constraints)
}
}

If you notice, we have moved boiler place code using extension.

How to use?

Let’s refactor code we wrote in the beginning by using addSubview() method.

fileprivate func setupName(){
 view.addSubview(lblName, constraints: 
[
lblName.centerXAnchor.constraint(equalTo: view.centerXAnchor),
lblName.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}

This view reduce the code drastically and you can be focused on only what is needed to setup.

Thanks for reading.Please feel to ask if you have any queries.

If you like this, please clap and support me.