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?
CodePudding user response:
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()
}
}
}
}