【问题标题】:Get age from range in SwiftUI DatePicker [closed]从 SwiftUI DatePicker 的范围内获取年龄 [关闭]
【发布时间】:2021-05-23 03:30:54
【问题描述】:

我正在做一个需要根据用户年龄进行计算的项目。

我想完全从 SwiftUI 开始,我可以做图形的东西,但我不知道如何使用这些信息。

所以我的标准代码是这样的:

struct ContentView: View {
    
    @State private var birthDate = Date()
    
    var body: some View{
        Form {
            DatePicker("Birth date:", selection: $birthDate, in: ...Date(), displayedComponents: .date).datePickerStyle(WheelDatePickerStyle()).font(.title)
        }
    }
}

我遇到的问题是如何从日期选择器中获取信息,然后计算用户的年龄以存储在变量中以供以后计算?

非常感谢您提供的任何帮助。

【问题讨论】:

标签: swift swiftui datepicker


【解决方案1】:

您可以使用.onChange 来跟踪birthDate 的变化,并在闭包内进行计算。

注意: SwiftUI 在main thread 中运行此闭包。所以如果你想在那里做昂贵的工作,你应该发送到background Queue 让 UI 顺利运行。

struct ContentView: View {
    
    @State private var birthDate = Date()
    @State private var age: DateComponents = DateComponents()
    
    var body: some View{
        VStack {
            Form {
                DatePicker("Birth date:", selection: $birthDate, in: ...Date(), displayedComponents: .date).datePickerStyle(WheelDatePickerStyle()).font(.title)
            }.onChange(of: birthDate, perform: { value in
                age = Calendar.current.dateComponents([.year, .month, .day], from: birthDate, to: Date())
        })
            Text("Age-> Years:\(age.year ?? 0) Months:\(age.month ?? 0) Days\(age.day ?? 0)")
        }
    }
}

【讨论】:

    猜你喜欢
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2015-04-14
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多