如何将 SwiftUI 框架中 DatePicker 的外观更改为仅几个月和几年? [英] How do I change the appearance of the DatePicker in the SwiftUI framework to only months and years?

查看:13
本文介绍了如何将 SwiftUI 框架中 DatePicker 的外观更改为仅几个月和几年?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改 DatePicker 的日期视图.我只想获得月份和年份的选择.我想在每次选择时将 ObservedObject 分配给一个变量.

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.

我的代码:

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

推荐答案

正如其他人已经评论的那样,您需要实现一个带有两个 Picker 的 HStack:

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

这篇关于如何将 SwiftUI 框架中 DatePicker 的外观更改为仅几个月和几年?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆