23 - iOS Autolayout
Autolayout
What have we used so far
- Dashed blue lines – edges and vertical/horizontal centers
- Ctrl-drag to edges and other elements (or itself) to set constraints
- Size inspector
- Click on constraint
- Document outline – fundamental to autolayout
Toolset
Buttons in lower right corner
- Update frames
- Align
- Add new constraints
- Resolve auto layout issues
- Embed in
Update frames
Update frames
- Recalculates all the positions/sizes and redraws layout
Align
- Align views to each-other
- Or to container
Add new constraints
- To nearest neighbor (click the dashed red line to add)
- Constrain to margins (not edges). Margin is 8dp on both sides of element edge
- Fix width or height
- Equal width or height between elements
- Aspect ratio (1:1 is square)
Resolve auto layout issues
-
Either for all the views or just selected
-
Add missing constraints
- Xcode trys to do magic - not vey good!
- Reset to Suggested Constraints
- Set everything according to blue dashed lines
-
Clear constraints
Embed in
Embed in
- Initially we are interested only in Stack View
- Groups selected view elements into new container
- Either horizontal or vertical
- Can control spacing, distribution, etc
- Somewhat similar to Constraint Layout Chains and Linear Layout in Android
Autolayout issues
But not everything is doable with constraints
- If screen is wildly different - no constraint system can help you
- In these cases we would like to have totally new positions, new constraints, show-or-hide some elements, change colors etc.
Size Classes
Apple has SIZE CLASSES
- Width: Compact or Regular (and Any)
- Heighth: Compact or Regular (and Any)
Size Classes - iPad
Size classes - problem
This is not what we want!
Variation
- You can edit many properties separately in different size classes.
- Click on + sign in front of property!
- X to remove
Constraint variation
You can do the same with constraints!
TIP! First select correct device in preview (with size class needed) - initial values are taken from preview size.
On older XCode
Select from the device selection the device size configuration you want to vary for From Vary fro Traits choose either Width or Height (or both) Device selection shows affected devices Modify Storyboard to your liking!
Autolayout In code
func updateLabel(){
let attributes: [NSAttributedString.Key: Any] = [
.strokeWidth : 5.0,
.strokeColor: colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.8470588235)
]
let attributedString = NSAttributedString(
string: traitCollection.verticalSizeClass == .compact ? "compact" : "regular",
attributes: attributes)
label.attributedText = attributedString
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateLabel()
}