Skip to content

Cross-Platform Size-Aware SwiftUI

Posted on:April 7, 2023

Some years ago, Paul Hudson wrote about the concept of an AdaptiveStack.

This is an excellent reusable stack-view, but it won’t work in cross-platform SwiftUI applications as the Mac doesn’t have a concept of size classes.

Luckily, we can add them fairly trivially with this extension:

#if os(macOS)
enum UserInterfaceSizeClass {
    case compact
    case regular
}

struct HorizontalSizeClassEnvironmentKey: EnvironmentKey {
    static let defaultValue: UserInterfaceSizeClass = .regular
}
struct VerticalSizeClassEnvironmentKey: EnvironmentKey {
    static let defaultValue: UserInterfaceSizeClass = .regular
}

extension EnvironmentValues {
    var horizontalSizeClass: UserInterfaceSizeClass {
        get { return self[HorizontalSizeClassEnvironmentKey.self] }
        set { self[HorizontalSizeClassEnvironmentKey.self] = newValue }
    }
    var verticalSizeClass: UserInterfaceSizeClass {
        get { return self[VerticalSizeClassEnvironmentKey.self] }
        set { self[VerticalSizeClassEnvironmentKey.self] = newValue }
    }
}
#endif

Happy hacking.