Here is the source
// ContentView.swift
// AdaptiveColorIssue
//
// Created by Stephen R Smith on 9/16/24.
//
import SwiftUI
struct ContentView: View {
@State var darkMode = false
let swatchHeight: CGFloat = 60
var body: some View {
VStack {
@Environment(\.colorScheme) var colorScheme
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
HStack {
RoundedRectangle(cornerRadius: 10)
.fill(Color("Adaptive"))
.frame(width: 100, height: swatchHeight)
VStack {
Text("\(Color("Adaptive").hexaRGB ?? "")")
Text(myResolvedColor(Color("Adaptive")))
}
}
HStack {
RoundedRectangle(cornerRadius: 10)
.fill(Color("NonAdaptive"))
.frame(width: 100, height: swatchHeight)
VStack {
Text("\(Color("NonAdaptive").hexaRGB ?? "")")
Text(myResolvedColor(Color("NonAdaptive")))
}
}
if captureColor(color: Color("Adaptive")) {
Text("")
}
}
.frame(width: 300, height: 200)
.colorScheme(darkMode ? .dark : .light)
.background(darkMode ? .black : .white)
.padding()
HStack {
RoundedRectangle(cornerRadius: 10)
.fill(Color("Adaptive"))
.frame(width: 100, height: swatchHeight)
VStack {
Text("\(Color("Adaptive").hexaRGB ?? "")")
Text(myResolvedColor(Color("Adaptive")))
}
}
HStack {
RoundedRectangle(cornerRadius: 10)
.fill(Color("NonAdaptive"))
.frame(width: 100, height: swatchHeight)
VStack {
Text("\(Color("NonAdaptive").hexaRGB ?? "")")
Text(myResolvedColor(Color("NonAdaptive")))
}
}
.padding()
Toggle("Darkmode", isOn: $darkMode)
.padding(40)
}
func captureColor(color: Color) -> Bool {
print ("Adaptive \(color.hexaRGB ?? "")")
return false
}
func myResolvedColor(_ color: Color) -> String {
let resolved = color.resolve(in: EnvironmentValues())
var clr: Color { Color(resolved) }
let ans = "\(clr.hexaRGB ?? "")"
return ans
}
}
#Preview {
ContentView()
}
extension Color {
var uiColor: UIColor { .init(self) }
typealias RGBA = (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)
var rgba: RGBA? {
var (r, g, b, a): RGBA = (0, 0, 0, 0)
return uiColor.getRed(&r, green: &g, blue: &b, alpha: &a) ? (r, g, b, a) : nil
}
var hexaRGB: String? {
guard let (red, green, blue, _) = rgba else { return nil }
return String(format: "#%02x %02x %02x",
Int(red * 255),
Int(green * 255),
Int(blue * 255)).uppercased()
}
var hexaRGBA: String? {
guard let (red, green, blue, alpha) = rgba else { return nil }
return String(format: "#%02x%02x%02x%02x",
Int(red * 255),
Int(green * 255),
Int(blue * 255),
Int(alpha * 255)).uppercased()
}
}
The "Adaptive" color set is "AnyAppearance"= #7F7F00, "dark"=#FFFF00
The "NonAdaptive" color is "Universal" = #9F0000
Toggle the "Darkmode" toggle to see that the hex value doesn't change.