how do i mix manual layout and auto layout
Asked on 07/31/2024
1 search
To mix manual layout and auto layout, you can use a combination of techniques from both UIKit and SwiftUI, as discussed in various WWDC sessions.
UIKit
In UIKit, you can use UIStackView
to handle dynamic layouts. A UIStackView
provides the logic needed to lay out subviews either vertically or horizontally by updating its axis property. You can determine the axis by checking the isAccessibilityCategory
property on the preferred content size category in the trait collection of the view controller. To respond to changes in text size while the app is running, subscribe to the UIContentSizeCategoryDidChangeNotification
and update the stack view accordingly.
For example:
let stackView = UIStackView()
stackView.axis = .vertical // or .horizontal based on your needs
You can also use automatic trait tracking in iOS 18, which simplifies handling trait changes. When layoutSubviews
is called, the horizontal size class trait usage is recorded, and the view automatically receives setNeedsLayout
to update for the new value.
SwiftUI
In SwiftUI, you can use the AnyLayout
type to dynamically switch between different layouts based on the environment. For instance, you can switch between HStack
and VStack
based on the text size.
Here's an example:
@Environment(\.dynamicTypeSize) var dynamicTypeSize
var dynamicLayout: AnyLayout {
if dynamicTypeSize.isAccessibilityCategory {
return AnyLayout(VStackLayout())
} else {
return AnyLayout(HStackLayout())
}
}
var body: some View {
dynamicLayout {
// Your content here
}
}
This approach allows you to adapt the layout dynamically based on the text size, providing a better user experience.
Relevant Sessions
- Get started with Dynamic Type (06:02)
- What’s new in UIKit (06:02)
These sessions provide detailed insights into handling dynamic layouts and trait changes in both UIKit and SwiftUI.

Explore Swift performance
Discover how Swift balances abstraction and performance. Learn what elements of performance to consider and how the Swift optimizer affects them. Explore the different features of Swift and how they’re implemented to further understand the tradeoffs available that can impact performance.

What’s new in UIKit
Explore everything new in UIKit, including tab and document launch experiences, transitions, and text and input changes. We’ll also discuss better-than-ever interoperability between UIKit and SwiftUI animations and gestures, as well as general improvements throughout UIKit.

Design Live Activities for Apple Watch
Starting in watchOS 11, Live Activities from your iOS app will automatically appear in the Smart Stack on a connected Apple Watch. Learn how to optimize the layout of your Live Activity for the wrist, and provide the right level of information and interactivity at the right time.