CS193P 8. View Controller Lifecycle, Autolayout

View Controller Lifecycle

  • Instantiated (from storyboard usually)
  • awakeFromNib
  • segue preparation happens
  • outlets get set
  • viewDidLoad

These pairs will be called each time your Controller’s view goes on/off screen …

  • viewWillAppear and viewDidAppear
  • viewWillDisappear and viewDidDisappear

These “geometry changed” methods might be called at any time after viewDidLoad …

  • viewWillLayoutSubviews (… then autolayout happens, then …) viewDidLayoutSubviews

If memory gets low, you might get …

  • didReceiveMemoryWarning

Autolayout

You’ve seen a lot of Autolayout already

  • Using the dashed blue lines to try to tell Xcode what you intend
  • Ctrl-Dragging between views to create relationships (spacing, etc.)
  • The “Pin” and “Arrange” popovers in the lower right of the storyboard
  • Reset to Suggested Constraints (if the blue lines were enough to unambiguously set constraints)
  • Document Outline (see all constraints, resolve misplacements and even conflicts)
  • Size Inspector (look at (and edit!) the details of the constraints on the selected view)
  • Clicking on a constraint to select it then bring up Attributes Inspector (to edit its details)

Mastering Autolayout requires experience

You just have to do it to learn it

Autolayout can be done from code too

Though you’re probably better off doing it in the storyboard wherever possible The demo today will show a simple case of doing Autolayout from code

Demo:

  • Notice auto layout issues and resove them.
  • Preview Storyboard in assistant editor
  • Remove magic nubmers in constraints of size inspector: such as use standard value or 0.

More:

What does “Use standard value and Constrain to Margins” mean in Auto Layout?

Auto Layout Concepts

The fundamental building block in Auto Layout is the constraint. Constraints express rules for the layout of elements in your interface;

Constraint Basics

You can think of a constraint as a mathematical representation of a human-expressable statement. If you’re defining the position of a button, for example, you might want to say “the left edge should be 20 points from the left edge of its containing view.” More formally, this translates to button.left = (container.left + 20), which in turn is an expression of the form y = m*x + b, where:

y and x are attributes of views.

m and b are floating point values.

An attribute is one of left, right, top, bottom, leading, trailing, width, height, centerX, centerY, and baseline.

Auto Layout Tutorial Part 1: Getting Started