Autolayout with Anchors in swift

  1. Using Auto Layout Visual Format Language.
  2. Using Layout Anchors.

Steps need to follow to add constraints:-

  • Call addSubview so that view is in the hierarchy.
  • Set translatesAutoresizingMaskIntoConstraints = false
  • Create constraints and set isActive = true to enable constraints.
  • When activating or deactivating lots of constraints at once, it’s more efficient to pass them as an array to activate() and deactivate() respectively.
  1. Create a view with background colour
let redView = UIView()
redView.backgroundColor = UIColor.red
redView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(redView)
redView.widthAnchor.constraint(equalToConstant: 100).isActive = true
redView.heightAnchor.constraint(equalToConstant: 100).isActive = true
NSLayoutConstraint.activate([
redView.widthAnchor.constraint(equalToConstant: 100),
redView.topAnchor.constraint(equalTo: view.topAnchor, constant: 50),
redView.heightAnchor.constraint(equalTo: redView.widthAnchor, multiplier: 1),
redView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])

API’s available for setting Constraints:-

open class NSLayoutXAxisAnchor : NSLayoutAnchor<NSLayoutXAxisAnchor>
open class NSLayoutDimension : NSLayoutAnchor<NSLayoutDimension>
open class NSLayoutYAxisAnchor : NSLayoutAnchor<NSLayoutYAxisAnchor>
  1. Use bellow methods for setting system spacing between to views
// for y axis
1. constraint(equalToSystemSpacingBelow anchor: NSLayoutYAxisAnchor, multiplier: CGFloat) -> NSLayoutConstraint
2. constraint(greaterThanOrEqualToSystemSpacingBelow anchor: NSLayoutYAxisAnchor, multiplier: CGFloat) -> NSLayoutConstraint
3. constraint(lessThanOrEqualToSystemSpacingBelow anchor: NSLayoutYAxisAnchor, multiplier: CGFloat) -> NSLayoutConstraint
// for x axis
4. constraint(equalToSystemSpacingAfter anchor: NSLayoutXAxisAnchor, multiplier: CGFloat) -> NSLayoutConstraint5. constraint(greaterThanOrEqualToSystemSpacingAfter anchor: NSLayoutXAxisAnchor, multiplier: CGFloat) -> NSLayoutConstraint6. constraint(lessThanOrEqualToSystemSpacingAfter anchor: NSLayoutXAxisAnchor, multiplier: CGFloat) -> NSLayoutConstraint
//for width and hight
1. constraint(equalTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint
2. constraint(greaterThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint
3. constraint(lessThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint
// for x and y axis
4. constraint(equalTo anchor: NSLayoutAnchor<AnchorType>) -> NSLayoutConstraint
5. constraint(greaterThanOrEqualTo anchor: NSLayoutAnchor<AnchorType>) -> NSLayoutConstraint
6. constraint(lessThanOrEqualTo anchor: NSLayoutAnchor<AnchorType>) -> NSLayoutConstraint

How can you set priority for constraints?

// added priority for width constraint
let
widthConstrain = redView.widthAnchor.constraint(equalToConstant: 100)
widthConstrain.priority = UILayoutPriority(rawValue: 999)
widthConstrain.isActive = true

What is aspect ratio and How can you set this?

  • Aspect ratio describes the ratio between the width and height of a view or screen.
  • A 1:1 aspect ratio, for example, is a square. The first number always refers to the width, and the second number refers to the height
  • You can set this property using multiplier.
//1:2 i.e view height is 2 times greater than it's width
redView.heightAnchor.constraint(equalTo: redView.widthAnchor, multiplier: 2)

How can we set content hugging and compression resistance?

//setting Content Hugging Priority horizontally
redView.setContentHuggingPriority(UILayoutPriority(rawValue: 999), for: .horizontal)
//setting Content Hugging Priority vertically
redView.setContentHuggingPriority(UILayoutPriority(rawValue: 999), for: .vertical)
//setting Compression Resistance Priority horizontally
redView.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 999), for: .horizontal)
//setting Compression Resistance Priority vertically
redView.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 999), for: .vertical)

Available layout guides:-

  1. LayoutMarginsGuide
  2. ReadableContentGuide
  3. SafeAreaLayoutGuide
  • Set constraints and keep the layout margins as spacing
/*
- It adds default UIEdgeInsets for the layout margin guide.
- If you want to change you can add additional edge insets by - view.layoutMargins = UIEdgeInsets(top: 150, left: 50, bottom: 50, right: 50)
- In iOS 11 and later, use the directionalLayoutMargins to define layoutMargins as:
view.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 150, leading: 50, bottom: 50, trailing: 50)
*/
// LayoutMarginsGuide for UIView
redView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor)
//ReadableContentGuide for UIViewredView.widthAnchor.constraint(equalTo: view.readableContentGuide.widthAnchor)
  • Represents the portion of your view that is unobscured by bars and other content.
  • Apple has deprecated topLayoutGuide & bottomLayoutGuide. So instead of having two dummy boxes, you now have one dummy box named safeAreaLayoutGuide on the UIView instance.
  • Want to know more about Safe Area? Read this excellent post by Evgeny Mikhaylov.
//SafeAreaLayoutGuide for UIView
redView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor)
// you can set the additionally safe area insets to view controller as:
viewController.additionalSafeAreaInsets = UIEdgeInsets(top: 150, left: 50, bottom: 50, right: 50)

Some of common error found while coding layouts:-

  1. Bellow error is because of setting redView.topAnchor to view.leftAnchor. It can be fixed by changing view.leftAnchor to NSLayoutYAxisAnchor like view.topAnchor or view.bottomAnchor.
redView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
redView.topAnchor.constraint(equalTo: view.centerYAnchor)

Animate changing Auto Layout constraints:-

UIView.animate(withDuration: 1.0) { [weak self] in
self?.imageToTopConstraint.isActive = false
self?.view.layoutIfNeeded()
}

External dependency when writing constraints in code:-

Debugging Auto Layout constraints:-

  • Constraints break can be easily identified by using identifier. It can be set as constraint.identifier = identifier name
let widthConstraint = redView.widthAnchor.constraint(equalToConstant: 100)// setting identifier to the constraint.
widthConstraint.identifier = "redView width constraint"
widthConstraint.isActive = true
  • You identify the Constraint Conflicts using these identifier. Now log look like this,

--

--

--

iOS Developer in walmart

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Navigation in Swift UI

Using Firebase in your Flutter Apps | Setting up everything

Frames and Bounds in a UIView (iOS)

Display GitHub Jobs in UITableView + Search

Building your own chart in iOS — Part 1: Bar chart (Revised)

The Dark Art of Building an Enterprise-Grade Mobile App — Part 2

Protocol-Delegation Pattern in Swift

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Manasa M P

Manasa M P

iOS Developer in walmart

More from Medium

how to covert sketchApp style “linear-gradient(-45deg, #00CC51 7%, #00CC8F 100%);” to swift?

Bees And Bomb Loading Animation Using SwiftUI

Swift — Create Call Animation in iOS inspired from Teams

Modern Collection Views with Compositional Layout_1