1

I'm in the process of migrating some code from UIKit to SwiftUI and I ran into an issue where displayGamut (e.g. sRGB vs. Display P3) does not appear to be available in the @Environment of SwiftUI. In UIKit you can get this from UITraitCollection.

Is there a way to get this natively in SwiftUI? If not, is there a way I can plumb this down into SwiftUI from the UIKit layer it's embedded in?

Logan Shire
  • 5,013
  • 4
  • 29
  • 37

1 Answers1

2

You can do this by creating your own custom EnvironmentKey for displayGamut, e.g.

struct DisplayGamut: EnvironmentKey {
    static var defaultValue: UIDisplayGamut {
        UITraitCollection.current.displayGamut
    }
}

extension EnvironmentValues {
    var displayGamut: UIDisplayGamut {
        self[DisplayGamut.self]
    }
}


struct ContentView: View {
    
    @Environment(\.displayGamut) var displayGamut
    
    var body: some View {
        VStack {
            switch displayGamut {
            case .P3:
                Text("displayGamut: P3")
            case .SRGB:
                Text("displayGamut: SRGB")
            case .unspecified:
                Text("displayGamut: unspecified")
            @unknown default:
                fatalError()
            }
        }
    }
}
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
  • Thanks! I was wondering if there was a more "official" way to get it but that makes sense. Do you know if SwiftUI views have a way to get the screen, though? E.g. for a macOS Catalyst application or an iPad connected to an external monitor, the external monitor might have a different display gamut than the device's main screen. I found this other thread where they were essentially plumbing it down from the UISceneDelegate: https://stackoverflow.com/questions/60359808/how-to-access-own-window-within-swiftui-view – Logan Shire Jan 17 '23 at 17:38