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

后端 未结 1 813
無奈伤痛
無奈伤痛 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..

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

    extension Binding {
        func onChange(_ completion: @escaping (Value) -> Void) -> Binding {
            .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)
提交回复
热议问题