iOS Auto Layout - kgleong/software-engineering GitHub Wiki

Auto Layout

Keyboard Shortcuts

  • ALT+CMD+= - aligns frames in interface builder that are misaligned according to their IB constraints.

Creating Views Programatically with AutoLayout

References

Constraints

Setting up constraints

  • Constraints should be set up in loadView or viewDidLoad. Use viewDidLoad if constraints neeed to be added after dynamic content has been laid out.
  • updateConstraints() - UIView method primarily used to batch update the contraints for multiple views. Overriding this method is rarely done.

References

Layout Guides

In iOS 9, layout guides were introduced to replace spacer or dummy views.

References

Layout Anchors

References

Content Size

References

Top and Bottom Layout Guides

The bottom layout guide refers to the bottom of the view.

For example, if a view is sitting on top of a tab bar, then the bottom layout guide will reference the top of the tab bar.

Compression Resistance

Content Hugging

Notifications

KeyboardWillShowNotification

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var bottomConstraint: NSLayoutConstraint!
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        /*
            Register an observer with the `UIKeyboardWillShowNotification`
            event that will call the specified method when the event occurs.
        */
        NSNotificationCenter
            .defaultCenter()
            .addObserver(
                self,
                selector: #selector(ViewController.keyboardWillAppear(_:)),
                name: UIKeyboardWillShowNotification,
                // Allows filtering of notifications by sender.  If
                // `object` is specified, only notifications sent by that
                // object are handled.
                object: nil
            )
    }

    /*
        Adjust the text field so it sits above the keyboard.
    */
    func keyboardWillAppear(notification: NSNotification) {
        /*
            `userInfo` is a dictionary containing information that the notification passes
            to its observers.

            `UIKeyboardFrameEndUserInfoKey` is the frame of the keyboard after the animation
            that shows the keyboard ends.

            The `CGRect` is wrapped in an `NSValue` object, which allows C structs (e.g.,
            `CGRect`, `CGPoint`, `CGSize`, etc.) to be stored in collections (e.g., arrays,
            dictionaries, etc.)

            To unwrap an `NSValue` object, call the method corresponding to the expected type.
            E.g., if a `CGRect` is expected, call `CGRectValue`
        */
        let heightToAdd = (notification.userInfo![UIKeyboardFrameEndUserInfoKey]! as! NSValue)
                              .CGRectValue().size.height

        self.bottomConstraint.constant += heightToAdd
    }

    deinit {
        /*
            Unsubscribe from all notifications to avoid attempted accesses
            to deallocated objects.
        */
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

References

Stack Views

Stack views have the following attributes:

  • axis - specifies the layout of the stack view, which can be either vertical or horizontal.
  • alignment - specifies how subviews are aligned within the stack view.
  • distribution - specifies how subview size and position will be determined.
  • spacing - numerical value that specifies the spacing in points between subviews.
Attribute Name Value Description
alignment Fill For the dimension that the stack view isn't managing, subviews will fill it completely. E.g., for a vertical stack view, the subviews will fill the entire width.
alignment Top, Center, Bottom (Horizontal) or Leading, Center, Trailing (Vertical)
alignment [First | Last] Baseline Aligns the specified baseline for all subviews. For multiline text, this aligns either the first or last lines.
distribution Equal Centering Request that the centers of each subview are equally spaced.
distribution Equal Spacing All subviews will be equally spaced apart, but will not be resized
distribution Fill One of the subviews is given priority based on the content hugging properties of all subviews. This subview is allotted most of the space, while the remaining subviews retain their defined sizes.
distribution Fill Evenly All subviews will be sized to take up an equal amount of space. All of the stack view's space will be used.
distribution Fill Proportionally Uses up all the space in the stack view, but keeps subview sizes proportionally equal to each other. For example, if one view is twice as large as another, the stack view will keep that proportion when scaling

References

References