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

后端 未结 1 810
無奈伤痛
無奈伤痛 2021-01-21 18:11

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.

My

相关标签:
1条回答
  • 2021-01-21 18:23

    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) }
    }
    
    0 讨论(0)
提交回复
热议问题