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

These sessions provide detailed insights into handling dynamic layouts and trait changes in both UIKit and SwiftUI.