swift - 在 SwiftUI 中使用 DatePicker 时如何将时间设置为标准值
问题描述
我的应用程序中有一个日期选择器,它只选择日期,而不是时间。看起来像这样:
DatePicker("Birthday",
selection: $date,
displayedComponents: [.date])
日期选择器为您提供了一个可以使用的日期对象。所以,当用户选择日期时,它当然也带有时间、时区等。我的问题是,时间默认设置为当前时间。但是,我需要将其始终设置为午夜。如何提供默认值?
我想到的一个可能的解决方案是使用格式化程序并将日期存储为字符串(而不是日期),但由于我需要稍后对其进行一些处理(例如计算两个日期之间的天数),所以这不会对我来说似乎是最好的方法。
解决方案
你可以试试这个:
struct ContentView: View {
@State var date = Date()
var body: some View {
VStack {
Text("\(date)")
DatePicker("Birthday", selection: $date, displayedComponents: [.date])
.onChange(of: date) { newDate in
if let midnight = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: newDate) {
date = midnight
}
}
}
}
}
或这个:
struct ContentView: View {
@State var date = Date()
var body: some View {
VStack {
Text("\(date)")
DatePicker("Birthday", selection: $date, displayedComponents: [.date])
}
.onAppear {
if let midnight = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date()) {
date = midnight
}
}
}
}
或这个:
struct ContentView: View {
@State var date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date())!
var body: some View {
VStack {
Text("\(date)")
DatePicker("Birthday", selection: $date, displayedComponents: [.date])
}
}
}
推荐阅读
- android - Kotlin:在 App 类中定义协程范围
- c# - MemoryMappedFile:为什么 CreateNew 在 Dispose 之后抛出?
- powershell - 解析导入 csv 并迭代管道值
- kubernetes-helm - 在 Azure Kubernetes 服务上安装 ISTIO 时将注解(创建私有负载均衡器)传递给 helm
- elasticsearch - 分析日志文件并显示结果的简单方法
- sqlite - 如何在一个查询中执行多个查询?
- docker - Docker for windows“服务器行为不端”从不同域的机器中提取图像时出错
- typescript - In Typescript is there a way to constrain an object to be a sub of another object without typing all fields as undefined?
- animation - QComboBox 弹出动画故障
- css - 继承(颜色)值的 CSS 自定义属性更改不起作用