I have this normal UIDatePicker
(sorry that it\'s not in English, please ignore that):
The GraphicalDatePickerStyle
in SwiftUI seems to be that second picker that appears after you click on the compact picker.
You should be able to use the UIViewController
below in a storyboard object and show the calendar.
class GraphicalDateViewController: UIViewController{
var datepicker: UIHostingController<CusDatePicker>? = nil
var dateVM: DatePickerViewModel = DatePickerViewModel()
private var dateCancellable: AnyCancellable?
override func viewDidLoad() {
super.viewDidLoad()
//Add Picker
datepicker = UIHostingController(rootView: CusDatePicker(vm: dateVM))
let idealSize = datepicker!.sizeThatFits(in: self.view.frame.size)
datepicker?.view.frame = CGRect(origin: CGPoint(x: self.view.frame.midX - idealSize.width/2, y: self.view.frame.midY - idealSize.height/2), size: idealSize)
//datepicker?.view.frame = CGRect(origin: CGPoint(x: self.view.frame.midX - 140, y: self.view.frame.midY - 140), size: CGSize(width: 280, height: 280))
addChild(datepicker!)
view.addSubview(datepicker!.view)
dateCancellable = dateVM.$currentDate.sink { currentDate in
self.render(currentDate: currentDate)
}
}
// MARK: DatePickerViewModel
private func render(currentDate: Date) {
print("GraphicalDateViewController" + #function)
print(currentDate.description)
}
}
class DatePickerViewModel: ObservableObject {
@Published var currentDate: Date = Date()
}
struct CusDatePicker: View {
@ObservedObject var vm: DatePickerViewModel
var body: some View {
//https://developer.apple.com/documentation/swiftui/datepicker
DatePicker("Date", selection: $vm.currentDate, displayedComponents: [.date, .hourAndMinute])
.datePickerStyle(GraphicalDatePickerStyle())
}
}
I don't know if this is still valid, but you can make use of the .inline
style of new UIDatePicker. Then use your own view and animations to mimic the appearance of the DatePicker from .compact
style.
let secondDatePicker = UIDatePicker()
secondDatePicker.preferredDatePickerStyle = .inline
self.view.addSubview(secondDatePicker)
secondDatePicker.translatesAutoresizingMaskIntoConstraints = false
secondDatePicker.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
secondDatePicker.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
If you want to continue using the wheels format, you can set the style to wheels on the story board,
or use this code
datePicker.preferredDatePickerStyle = .wheels