SwiftUI - Date Picker display Year Only

Viewed 2870

Is it possible to use Apple's very own date picker and display just the year only?

This is my current code:

  DatePicker("", selection: $cameraViewModel.age, displayedComponents: .date)
        .datePickerStyle(CompactDatePickerStyle())

Of course the .displayedComponents would allow me to alter the UI/elements however, there's no call for just the year.

Thank you. I have searched Stackoverflow, found a thread, but the OP never followed up.

1 Answers

I don't think you can do this with a DatePicker - it's for selecting a Date and a year is just a simple Int.

Displaying a year only can be achieved with a standard Picker (although the appearance may differ):

struct ContentView: View {
    @State var selection = Date()
    var body: some View {
        Picker("", selection: $selection) {
            ForEach(2000...2020, id: \.self) {
                Text(String($0))
            }
        }
        .pickerStyle(InlinePickerStyle())
    }
}
Related