首页 > 解决方案 > 从 SwiftUI DatePicker 的范围内获取年龄

问题描述

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

我想完全从 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)
        }
    }
}

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

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

标签: swiftswiftuidatepicker

解决方案


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

注意: SwiftUI 在main thread. 所以如果你想在那里做昂贵的工作,你应该派遣到 abackground 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)")
        }
    }
}


推荐阅读