Search code examples
swiftdatepickerswiftuipicker

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


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)
                    }
 }

Solution

  • 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) }
    }