How do I change the appearance of the DatePicker in the SwiftUI framework to only months and years?
Asked Answered
Y

1

2

I want to change the DatePicker's date view. I just want to get a month and year selection. I want to assign ObservedObject to a variable at each selection.

enter image description here

My Code:

 @State private var date = Date()

 var body: some View {
          DatePicker("", selection: $date, in: Date()..., displayedComponents: .date)
                    .labelsHidden()
                    .datePickerStyle(WheelDatePickerStyle())
                    .onDisappear(){
                        let dateFormatter = DateFormatter()
                        dateFormatter.dateFormat = "MM/yyyy"
                        self.cardData.validThru = dateFormatter.string(from: self.date)
                    }
 }
Yamamoto answered 8/6, 2020 at 21:41 Comment(3)
This answer is similar: How create a MonthPicker in SwiftUI?Fronde
There's no answer there to solve the problem.Yamamoto
I think they suggest to use two Pickers (not DatePickers).Fronde
F
3

As others have already commented You would need to implement an HStack with two Pickers:

struct ContentView: View {

    @State var monthIndex: Int = 0
    @State var yearIndex: Int = 0

    let monthSymbols = Calendar.current.monthSymbols
    let years = Array(Date().year..<Date().year+10)

    var body: some View {
        GeometryReader{ geometry in
            HStack(spacing: 0) {
                Picker(selection: self.$monthIndex.onChange(self.monthChanged), label: Text("")) {
                    ForEach(0..<self.monthSymbols.count) { index in
                        Text(self.monthSymbols[index])
                    }
                }.frame(maxWidth: geometry.size.width / 2).clipped()
                Picker(selection: self.$yearIndex.onChange(self.yearChanged), label: Text("")) {
                    ForEach(0..<self.years.count) { index in
                        Text(String(self.years[index]))
                    }
                }.frame(maxWidth: geometry.size.width / 2).clipped()
            }
        }  
    }
    func monthChanged(_ index: Int) {
        print("\(years[yearIndex]), \(index+1)")
        print("Month: \(monthSymbols[index])")
    }
    func yearChanged(_ index: Int) {
        print("\(years[index]), \(monthIndex+1)")
        print("Month: \(monthSymbols[monthIndex])")
    }
}

You would need this helper from this post to monitor the Picker changes

extension Binding {
    func onChange(_ completion: @escaping (Value) -> Void) -> Binding<Value> {
        .init(get:{ self.wrappedValue }, set:{ self.wrappedValue = $0; completion($0) })
    }
}

And this calendar helper

extension Date {
    var year: Int { Calendar.current.component(.year, from: self) }
}
Fuscous answered 9/6, 2020 at 2:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.