Member-only story
SwiftUI T-3
4 min readDec 17, 2024
SwiftUI Adaptive Layout
Requirement 1: adapts dynamically based on the device’s orientation (Portrait vs. Landscape).
Key Requirements:
- In Portrait Mode:
- Content arranged vertically (VStack) → Image on top, text below.
- In Landscape Mode:
- Content arranged horizontally (HStack) → Image on the left, text on the right.
Solution Outline:
- Detect Orientation
UseGeometryReader
to capture the view’s size (width and height). Based on these dimensions:
- If
width > height
→ Landscape. - Else → Portrait.
2. PreferenceKey
In SwiftUI, a PreferenceKey is a protocol used to pass data up the view hierarchy. It enables child views to communicate information to their parent views, even if those parents are several levels up the view hierarchy.
This is particularly useful when:
- You need to share layout-related data or custom preferences from child views to parent views.
- SwiftUI’s built-in data passing mechanisms (like
@Environment
or@Binding
) are not suitable.
How PreferenceKey Works
- A
PreferenceKey
is a type that conforms to thePreferenceKey
protocol. - It requires a
defaultValue
and areduce
function to combine values from multiple children.