Skip to content

Latest commit

 

History

History

day-031

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Day 31: Project 6, Part Two

Follow along at https://www.hackingwithswift.com/100/31.

📒 Field Notes

This day covers the second and final part of Project 6: Auto Layout in Hacking with Swift.

I have a separate repository where I've been creating projects alongside the material in the book. And you can find Project 6 here. However, I also copied it over to Day 30's and began extending it from where I left off.

With that in mind, Day 31 focuses on several specific topics, followed by some challenges:

  • Auto Layout metrics and priorities: constraints(withVisualFormat:)
  • Auto Layout anchors

Auto Layout metrics and priorities: constraints(withVisualFormat:)

I hinted at it in Day 30, but metrics and priorities allow us to give our VFL strings more information density, making them more maintainable and, often, more readable at the same time:

let metrics = ["labelHeight": 88]

let layoutString = V:|[label1(labelHeight@999)]|

Even better, when we want to reuse a specific combination of metrics and priorities, we can reference the key name of the original element using it:

let metrics = ["labelHeight": 88]

let layoutString = "[label1(labelHeight@999)]-[label2(label1)]-[label3(label1)]-[label4(label1)]-[label5(label1)]"

Ultimately, it's all the same to NSLayoutConstraint.constraints(withVisualFormat:) — but that's beside the point 😀.

Auto Layout anchors

As a language nerd, I can't help but like VFL. But it has to be practical if I'm going to use it. For intricate, uncommon designs, VFL may well be the right tool, but often, we'll be better off leveraging the anchors that belong to UIView.

The have a nice functional, declarative interface for setting constraints, and we can even reference other anchors:

for label in labels {
    label.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
    label.heightAnchor.constraint(equalToConstant: 88).isActive = true
}

🥅 Challenges

Challenge 1

Try replacing the widthAnchor of our labels with leadingAnchor and trailingAnchor constraints, which more explicitly pin the label to the edges of its parent.

Challenge 2

Once you’ve completed the first challenge, try using the safeAreaLayoutGuide for those constraints.

Challenge 3

Try making the height of your labels equal to 1/5th of the main view, minus 10 for the spacing.

🔗 Additional/Related Links