Reputation: 69
I am trying to add a UIDatePicker to a set of text fields which are already present. I am unable to set the UI Date picker to the bottom of the screen even after trying all the solutions I see on StackOverflow. I am using the MVVM model and I have created a separate file for creating the Picker view.
class UAFieldDatePickerView: UIStackView {....}
extension UAFieldDatePickerView {
@objc private func didTapDateView() {
guard viewModel.state.value != .disabled else {
return
}
let datePicker = UIDatePicker()
datePicker.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - 200, width: self.frame.size.width, height: 200)
datePicker.backgroundColor = UIColor.UANeutralGray05
datePicker.datePickerMode = .date
datePicker.date = Calendar.current.date(byAdding: .day, value: -1, to: Date())!
datePicker.addTarget(self, action: #selector(datePickerValueChanged(_:)), for: .valueChanged)
self.addSubview(datePicker)
}
@objc func datePickerValueChanged(_ datePicker: UIDatePicker) {
datePicker.maximumDate = Date()
}
}
The problem I face is not being able to pin the DatePicker to the bottom of the screen. How Will I be able to ensure that the frame is always pinned to the bottom.
Upvotes: 1
Views: 1737
Reputation: 125007
UIDatePicker
descends from UIControl
, which means it's also a subclass of UIView
, and it follows the same rules that any other view does. If you want a date picker positioned at the bottom of the screen, then you need to put it there.
datePicker.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - 200, width: self.frame.size.width, height: 200)
Here you're setting the vertical position of the date picker to the screen height minus the height of the picker. But you're not adding the picker to the screen, you're adding it to self
. If you want the picker to be positioned at the bottom of the view that you're adding it to, then you should calculate the height based on that view, not based on something else that might or might not have the same size. Since you're adding the picker to self
, use self.bounds.size.height
to calculate the position:
datePicker.frame = CGRect(x: 0, y: self.bounds.size.height - 200, width: self.bounds.size.width, height: 200)
If you want the picker to be at the bottom of the screen, then either take steps to ensure that the view that contains it is positioned at the bottom of the screen, or display the picker a different way. CZ54's suggestion in comments to use the picker as an input view is a good one; a more general way to do something similar is to present the date picker modally from the bottom of the screen.
Upvotes: 2