swift - 从 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)
}
}
}
我遇到的问题是如何从日期选择器中获取信息,然后计算用户的年龄以存储在变量中以供以后计算?
非常感谢您提供的任何帮助。
解决方案
您可以使用.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)")
}
}
}
推荐阅读
- vespa - Vespa 中的第三方 API 调用
- python - NFA 的 Python 正则表达式
- java - PCF(Pivotal CLoud Foundry)正在将内容长度附加到我的应用程序中
- reactjs - 添加取消图标以关闭 Material-UI Drawer
- bash - 如何在 shell for 循环中延迟评估命令
- selenium - 量角器 browser.manage().logs().get('performance') 未检索服务器响应正文
- java - UriComponentsBuilder - 如何替换一些查询参数并删除未使用的?
- java - Apollo GraphQL Android 无法解决“无法解析 http 响应”错误
- html - z-index 会影响线性背景吗?
- unix - 计算文件中存在的日期与今天日期之间的天差