Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
UIDatePicker wrapper in SwiftUI
//
// TimePicker.swift
//
// Created by Tobias Stikvoort on 16/11/2021.
//
import SwiftUI
import UIKit
struct TimePicker: UIViewRepresentable {
@Binding var date: Date
let minimumDate: Date?
let maximumDate: Date?
func makeUIView(context: Context) -> UIDatePicker {
let picker = UIDatePicker()
picker.datePickerMode = .time
picker.preferredDatePickerStyle = .wheels
picker.minuteInterval = 5
picker.minimumDate = minimumDate
picker.maximumDate = maximumDate
picker.addTarget(context.coordinator, action: #selector(Coordinator.valueChanged(_:)), for: .valueChanged)
return picker
}
func updateUIView(_ picker: UIDatePicker, context: Context) {
picker.date = date
picker.minimumDate = minimumDate
picker.maximumDate = maximumDate
}
func makeCoordinator() -> Coordinator {
Coordinator(date: $date)
}
class Coordinator: NSObject {
@Binding private var date: Date
init(date: Binding<Date>) {
_date = date
}
@objc func valueChanged(_ sender: UIDatePicker) {
date = sender.date
}
}
}
struct TimePicker_Previews: PreviewProvider {
@State static var date: Date = Date.now
static var previews: some View {
TimePicker(date: $date, minimumDate: Date.now, maximumDate: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment