[英]How to convert String to Binding<Date> in DatePicker SwiftUI?
I want to set DatePicker from a String to a certain date when it appears.我想在 DatePicker 出现时将它从 String 设置为某个日期。
@State var staff: Staff
DatePicker(selection: $staff.birthDate, in: ...Date(),displayedComponents: .date) {
Text("Birth Date:")
}
What I expect is something like that, but it didn't work because selection requires Binding<Date>
and $staff.birthDate
is a String.我期望的是类似的东西,但它不起作用,因为选择需要
Binding<Date>
并且$staff.birthDate
是一个字符串。 How do I convert it?我该如何转换它?
I tried to create a func to format it like so:我试图创建一个函数来像这样格式化它:
func formatStringToDate(date: String?) -> Binding<Date> {
@Binding var bindingDate: Date
let dateForm = DateFormatter()
dateForm.dateFormat = "dd-MM-YYYY"
// _bindingDate = date
return dateForm.date(from: date ?? "")
}
But it still doesn't work.但它仍然不起作用。 Any idea on how to solve this?
关于如何解决这个问题的任何想法? Or did I approach this wrong?
还是我做错了?
Thankyou in advance.先感谢您。
You need to use another date parameter for birth date.您需要为出生日期使用另一个日期参数。 So your Staff class is
所以你的员工 class 是
class Staff: ObservableObject {
@Published var birthDate: String = "02-05-2021"
@Published var date: Date = Date()
init() {
self.date = DateFormatter.formate.date(from: birthDate) ?? Date()
}
}
Now create one date formattter in the DateFormatter
extension.现在在
DateFormatter
扩展中创建一个日期格式化程序。
extension DateFormatter {
static var formate: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
return dateFormatter
}
}
Now, in view struct use the .onChange
method.现在,在视图结构中使用
.onChange
方法。 It will execute each time when the date is changed and you need to convert this date to a string and store it in your birthDate string var.每次更改日期时它都会执行,您需要将此日期转换为字符串并将其存储在您的birthDate字符串var中。
struct ContentView: View {
@StateObject var staff: Staff = Staff()
var body: some View {
DatePicker(selection: $staff.date, in: ...Date(),displayedComponents: .date) {
Text("Birth Date:")
}
.onChange(of: staff.date) { (date) in
staff.birthDate = DateFormatter.formate.string(from: date)
}
}
}
If your project target is from iOS 13 then you can use custom binding.如果您的项目目标来自 iOS 13,那么您可以使用自定义绑定。
struct ContentView: View {
@StateObject var staff: Staff = Staff()
var body: some View {
DatePicker(selection: Binding(get: {staff.date},
set: {
staff.date = $0;
staff.birthDate = DateFormatter.formate.string(from: $0)
}), in: ...Date(),displayedComponents: .date) {
Text("Birth Date:")
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.