SwiftUI's colorScheme vs preferredColorScheme

SwiftUI's colorScheme modifier is said to be deprecated in favour of preferredColorScheme but the two work differently. See the below sample app, colorScheme changes the underlying view colour while preferredColorScheme doesn't. Is that a bug of preferredColorScheme?

import SwiftUI

struct ContentView: View {
    let color = Color(light: .red, dark: .green)
    
    var body: some View {
        VStack {
            HStack {
                color.colorScheme(.light)
                color.colorScheme(.dark)
            }
            HStack {
                color.preferredColorScheme(.light)
                color.preferredColorScheme(.dark)
            }
        }
    }
}

#Preview {
    ContentView()
}

@main struct TheApp: App {
    var body: some Scene {
        WindowGroup { ContentView() }
    }
}

extension UIColor {
    convenience init(light: UIColor, dark: UIColor) {
        self.init { v in
            switch v.userInterfaceStyle {
            case .light: light
            case .dark: dark
            case .unspecified: fatalError()
            @unknown default: fatalError()
            }
        }
    }
}

extension Color {
    init(light: Color, dark: Color) {
        self.init(UIColor(light: UIColor(light), dark: UIColor(dark)))
    }
}

Hello yetanotherme,

As per the discussion of preferredColorScheme(_:):

If there are conflicting, non-nil color scheme preferences set by parallel branches of the view hierarchy, the system will prioritize the first non-nil preference based on the order of the views.

Thus in your sample code, your initial preference set of .light should take precedence. When you swap lines 13 and 14, .dark sets both rectangles to be green, instead.

Thank you for your patience,

Richard Yeh ||  Developer Technical Support

SwiftUI's colorScheme vs preferredColorScheme
 
 
Q