iOS@Taipei
iOS
concise-swift
UIStackView
This post is for those who use code layout and feel unhappy about so many constraints and offsets/insets should define and set.
It's really the time to reduce code layout process time and take more time on learning SwiftUI
.
Warning
In this post we useUIStackView
andlayoutMargins
for building concise custom view, that may not suitable for complex animation.
let's not talk about frame-layout
maintainability.
When building custom view, we have to make sure the subviews of the custom view share the size and spaces correctly, also we might want some padding on custom view or on those subviews.
If we use pure Autolayout
, it will be hard to deal with specific design requirement. Says we have to make sure 5 UI element horizontal spaces always equal to 5
, we have to anchor each of them horizontal space 4
times to make it happen.
Also when we want to set four direction padding for different value, you have to do four times anchor to make it.
Even if we using SnapKit
, if the padding value is not the same, we still have to write code like:
First, let's talk about how to make adpative custom view layout easier.
In WWDC15 session Mysteries of Auto Layout, Part 1 says UIStackView
is maintainable layout. There's many handy properties to set in UIStackView
and it can really help you to arrange subviews in autolayout.
The session also says that since UIStackView
doesn't need to render background, so it is optimized to render fast than normal view.
The Session Conclusion
Start with Stack View, use constraints as needed.
Before using UIStackView, you may write code like:
With UIStackView
, you can make concise and component-style code layout:
Plus, you can use factory method like makeButtonStackView()
to make your layout logic more readable.
In WWDC18 session UIKit: Apps for Every Size and Shape introduce layoutMargins
and layoutMarginsGuide
.
layoutMargins are padding and the layoutMarginsGuide is the square that define space inside the padding.
We use layoutMarginsGuide to hook autolayout anchor inside the layoutMargins
just like using safeAreaLayoutGuide to make sure the our view is in the safeAreaInsets.
Let me show you how to use layoutMarginsGuide
to take your layout code readibility to the next level.
If we use UIStackView
, layoutMarginsGuide
, factory method and meaningful enum, we can make code really concise and easy to change any layout.
Set .preservesSuperviewLayoutMargins
to true can make superview's layoutMargins
affect subview, so the entire view can set layoutMargins
just once. If you subview has animation any may go outside to superview's layoutMargins
, you should set it to false
.