简体   繁体   中英

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.

@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. 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 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.

extension DateFormatter {
    static var formate: DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy"
        return dateFormatter
    }
}

Now, in view struct use the .onChange method. 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.

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.

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:")
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM