Search This Blog

Showing posts with label NSLayoutConstraint. Show all posts
Showing posts with label NSLayoutConstraint. Show all posts

Saturday, November 11, 2017

Ways to create NSLayoutConstraint

There are a lot of ways to work with AutoLayout and Constraints. You can specify constraints using different techniques. Here I enumerate methods that I know:
  1. Using UIBuilder and Storyboard
  2. Using code and constraint method
  3. Using code and NSLayoutConstraint constructor
  4. Create Constraints with Visual Format 
  5. Using Framework - SnapKit
We will make simple task - create view of size: width 240, height 128, and center it vertically and horizontally.

1. Using UIBuilder


Adding width and height constraints


Align center vertically and horizontally

There are 4 constraints 

Result


2. Using code - way 1 - constraint method


Activate each constraint separately.
override func viewDidLoad() {
    super.viewDidLoad()
        
    let customView = UIView()
    customView.backgroundColor = UIColor.lightGray
    // 1. Add your view as subview
    self.view.addSubview(customView)
    // 2. Activate AutoLayout
    customView.translatesAutoresizingMaskIntoConstraints = false
    // 3. Activate Constraints
    customView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
    customView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
    customView.widthAnchor.constraint(equalToConstant: 240).isActive = true
    customView.heightAnchor.constraint(equalToConstant: 128).isActive = true
}

Or it can be done differently - activate all constraints together.
NSLayoutConstraint.activate([
    customView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
    customView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
    customView.widthAnchor.constraint(equalToConstant: 240),
    customView.heightAnchor.constraint(equalToConstant: 128)
 ])

3. Using code - way 2 - NSLayoutConstraint constructor


Another way to create NSLayoutConstraint
let centerXConstraint = NSLayoutConstraint(item: customView,
                                                   attribute: .centerX,
                                                   relatedBy: .equal,
                                                   toItem: self.view,
                                                   attribute: .centerX,
                                                   multiplier: 1,
                                                   constant: 0)
let centerYConstraint = NSLayoutConstraint(item: customView,
                                                   attribute: .centerY,
                                                   relatedBy: .equal,
                                                   toItem: self.view,
                                                   attribute: .centerY,
                                                   multiplier: 1,
                                                   constant: 0)
let widthConstraint = NSLayoutConstraint(item: customView,
                                                   attribute: .width,
                                                   relatedBy: .equal,
                                                   toItem: nil,
                                                   attribute: .notAnAttribute,
                                                   multiplier: 1,
                                                   constant: 240)
let heightConstraint = NSLayoutConstraint(item: customView,
                                                   attribute: .height,
                                                   relatedBy: .equal,
                                                   toItem: nil,
                                                   attribute: .notAnAttribute,
                                                   multiplier: 1,
                                                   constant: 128)

NSLayoutConstraint.activate([centerXConstraint, centerYConstraint, widthConstraint, heightConstraint])

Or, for activation of constraints, instead of NSLayoutConstraint.activate() we can use method of parent view addConstraints
self.view.addConstraints([centerXConstraint, centerYConstraint, widthConstraint, heightConstraint])

4. Create Constraints with Visual Format 

There is one more way to create constraints. It is called Visual Format. For creating constraint you must provide description of it with special syntax. V for Vertical constraints, H for Horizontal.
self.view.addConstraints(NSLayoutConstraint.constraints(
            withVisualFormat: "V:[customView(128)]",
            options: NSLayoutFormatOptions(),
            metrics: nil,
            views: ["customView": customView]))
self.view.addConstraints(NSLayoutConstraint.constraints(
            withVisualFormat: "H:[customView(240)]",
            options: NSLayoutFormatOptions(),
            metrics: nil,
            views: ["customView": customView]))
self.view.addConstraints(NSLayoutConstraint.constraints(
            withVisualFormat: "V:[superView]-(<=1)-[customView]",
            options: NSLayoutFormatOptions.alignAllCenterX,
            metrics: nil,
            views: ["customView": customView, "superView": self.view]))
self.view.addConstraints(NSLayoutConstraint.constraints(
            withVisualFormat: "H:[superView]-(<=1)-[customView]",
            options: NSLayoutFormatOptions.alignAllCenterY,
            metrics: nil,
            views: ["customView": customView, "superView": self.view]))

5. Using Framework - SnapKit

NSLayoutConstraints as Apple provide it is not most handy thing. So there is a framework which simplify creation of constraints.

You can get it here - SnapKit Framework

import SnapKit

let customView = UIView()
customView.backgroundColor = UIColor.lightGray
self.view.addSubview(customView)
customView.snp.makeConstraints { (maker) in
    maker.width.equalTo(240)
    maker.height.equalTo(128)
    maker.centerX.equalTo(self.view)
    maker.centerY.equalTo(self.view)
}