How to set a tint for a DatePicker in SwiftUI?

722 Views Asked by At

In iOS 16 accentColor(_:) modifier has been deprecated, and Apple suggests using tint(_:) instead.

However, I found it does not work on the DatePicker. It works as expected on the Button, for instance. I was experimenting with applying .tint modifier on different levels but without success. .accentColor works as expected, though.

  • In the example, I apply .purple tint to the entire List view, so I expect it will be applied to all subviews.
  • I apply .red tint to the DatePicker, which should override parent's tint. In the result, it has neither its own tint nor its parent's tint – it's the default (.blue) – not as expected.
  • I apply .green tint to the first Button and it overrides parent's tint – as expected.
  • I do not apply any tint to the second Button, so it inherits parent's tint (.purple) – as expected.
struct ContentView: View {
    @State private var date = Date()
    var body: some View {
        List {
            DatePicker("Date", selection: $date, displayedComponents: [.date])
                .datePickerStyle(.graphical)
                .tint(.red) // <- doesn't work
            Button("Button with own tint") { }
                .buttonStyle(.borderedProminent)
                .tint(.green) // <- works
            Button("Button with parent tint") { }
                .buttonStyle(.borderedProminent)
        }
        .tint(.purple) // <- works on Button, but not on DatePicker
    }
}

DatePikcer test view

Am I doing something wrong, or is it some kind of SwiftUI's bug?

2

There are 2 best solutions below

2
mongrong On

enter image description here

It seems that the color is converted by using colorInvert and colorMultiple.

import SwiftUI

struct ContentView: View {
    @State private var date = Date()
    var body: some View {
        List {
            DatePicker("Date", selection: $date, displayedComponents: [.date])
                .colorInvert()
                .colorMultiply(.red)
                .datePickerStyle(.graphical)
                
            Button("Button with own tint") { }
                .tint(.green) // <- works
                .buttonStyle(.borderedProminent)
                
            Button("Button with parent tint") { }
                .buttonStyle(.borderedProminent)
        }
        .tint(.purple) // <- works on Button, but not on DatePicker
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
0
Ryba On

It looks like a bug in Xcode 14 / iOS 16.0.

Code posted by me in the question, works as expected on Xcode 14.1 RC and iOS 16.1.