xcodedatepickerswiftuiuidatepicker

SwiftUI: how to create custom UIDatePicker?


I succeeded to create UIDatePicker inside SwifUI, but when I change the date wheel in picker the date value not update, here is my code:

struct DatePicker: UIViewRepresentable {
    @Binding var date: Date
    
    func makeUIView(context: Context) -> UIDatePicker {
        let view = UIDatePicker()
        view.datePickerMode = .date
        return view
    }
    func updateUIView(_ uiView: UIDatePicker, context: Context) {
        uiView.date = date
    }
}

Then I call it from the view like this:

struct SwiftUIView: View {
  @State var date = Date()
    var body: some View {
      DatePicker(date: self.$date)
  }
}

Solution

  • Here is possible approach. Tested with Xcode 11.2 / iOS 13.2

    struct DatePicker: UIViewRepresentable {
        @Binding var date: Date
    
        func makeUIView(context: Context) -> UIDatePicker {
            let datePicker = UIDatePicker()
            datePicker.datePickerMode = .date
            datePicker.addTarget(context.coordinator, action: #selector(Coordinator.changed(_:)), for: .valueChanged)
            return datePicker
        }
    
        func updateUIView(_ datePicker: UIDatePicker, context: Context) {
            datePicker.date = date
        }
    
        func makeCoordinator() -> DatePicker.Coordinator {
            Coordinator(date: $date)
        }
    
        class Coordinator: NSObject {
            private let date: Binding<Date>
    
            init(date: Binding<Date>) {
                self.date = date
            }
    
            @objc func changed(_ sender: UIDatePicker) {
                self.date.wrappedValue = sender.date
            }
        }
    }