Submitted by: Submitted by wesley930927
Views: 48
Words: 594
Pages: 3
Category: Science and Technology
Date Submitted: 11/30/2014 06:21 PM
Mobile Application Programming in iOS
CS-GY9033 Fall 2014 Session 5
AutoLayout
•
Layout System that is:
• • •
Constraint-based Dynamic Descriptive
Before AutoLayout
•
Hardcoded layout based on Frame
UIView.init(frame: CGRect(x: 0, y: 0, width: 120, height: 240))
Fixed Layout Problems
• • •
Can’t handle rotation well Can’t handle different devices Lots of math and exception
What Layout Do We Want?
•
Center of Button == Center of View
Button.center.x == superview.center.x
•
Bottom of Button == Bottom of View Padding
Button.bottom == superview.bottom - padding
AutoLayout Demo 1
AutoLayout coding
•
Remember simple formula:
item1.attribute = multiplier x item2.attribute + constant
• •
Doesn’t have to be equality (, =) Use the class: NSLayoutConstraint
NSLayoutConstraint
convenience init(item view1: AnyObject!, attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation, toItem view2: AnyObject!, attribute attr2: NSLayoutAttribute, multiplier multiplier: CGFloat, constant c: CGFloat)
enum NSLayoutAttribute : Int { case Left case Right case Top case Bottom case Leading case Trailing case Width case Height case CenterX case CenterY case Baseline case NotAnAttribute } enum NSLayoutRelation : Int { case LessThanOrEqual case Equal case GreaterThanOrEqual }
Why NSLayoutConstraint Code?
• • •
Understand the underlying mechanism Runtime constraints (building views dynamically) Sometime you just can’t do it in Interface Builder
Adding Constraints to Views
UIView methods:
func addConstraint(_ constraint: NSLayoutConstraint) func addConstraints(_ constraints: [AnyObject]) func removeConstraint(_ constraint: NSLayoutConstraint) func removeConstraints(_ constraints: [AnyObject])
Where to add Constraints?
• • • •
Closest View object that contains constrained Views Sibling Views => Parent View Cousin Views => Grandparent View...