History
Loading...
Loading...
September 22, 2025
@Environment(\.horizontalSizeClass) and @Environment(\.verticalSizeClass) to create truly responsive layouts that adapt to different device orientations and screen sizes. These environment values automatically update when the device rotates or when your app runs on different devices.This pattern uses size classes to determine the optimal layout structure, switching between vertical stacking for compact spaces and horizontal layouts for regular size classes. The computed property `isCompact` simplifies the conditional logic.
struct AdaptiveContentView: View {
@Environment(\.horizontalSizeClass) var horizontalSize
@Environment(\.verticalSizeClass) var verticalSize
var isCompact: Bool {
horizontalSize == .compact || verticalSize == .compact
}
var body: some View {
Group {
if isCompact {
VStack(spacing: 16) {
ProfileSection()
ActionButtons()
ContentGrid(columns: 1)
}
} else {
HStack(spacing: 24) {
VStack {
ProfileSection()
ActionButtons()
}
.frame(maxWidth: 300)
ContentGrid(columns: 2)
}
}
}
.padding()
.animation(.easeInOut(duration: 0.3), value: horizontalSize)
}
}Size class-based layouts ensure your app looks great on all devices and orientations without hardcoding specific device types. This approach is more maintainable than device-specific checks and automatically adapts to future screen sizes and multitasking scenarios.