iOS Swift UIDatePicker inline style time and days title not display when set on inputView

2.5k Views Asked by At

I use inline UIDatePicker with dateAndTime mode as inputView for TextField. However, it not display time and days title. Like below image.

enter image description here

Below are my code for set UIDatePicker:-

    func setupDatePicker() {
        datePicker = UIDatePicker()
        datePicker?.date = Date()
        datePicker?.locale = .current
        datePicker?.minimumDate = Date()
        datePicker?.datePickerMode = .dateAndTime
        if #available(iOS 14.0, *) {
            datePicker?.preferredDatePickerStyle = .inline
        }
        datePicker?.addTarget(self, action: #selector(handleDateSelection), for: .valueChanged)
        
        txtDate.inputView = datePicker
    }

Please help me how to show time and days title in this like below.

enter image description here]

Thanks in advance.

1

There are 1 best solutions below

0
maga On

There is a workaround for this. The idea is to wrap UIDatePicker inside of another UIView which frame provides enough space to display entire UIDatePicker. Then use auto-layouts for UIDatePicker to snap edges to the superview or just update the frame to match superview.

Code snippet:

let picker = UIDatePicker()

// Your additional code to set up `UIDatePicker`

if #available(iOS 14.0, *) {
    picker.preferredDatePickerStyle = .inline
}

// Big enough frame
let rect = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 420)
let pickerWrapperView = UIView(frame: rect)
pickerWrapperView.addSubview(picker)

// Adding constraints
picker.translatesAutoresizingMaskIntoConstraints = false
picker.leadingAnchor.constraint(equalTo: pickerWrapperView.leadingAnchor).isActive = true
picker.trailingAnchor.constraint(equalTo: pickerWrapperView.trailingAnchor).isActive = true
picker.topAnchor.constraint(equalTo: pickerWrapperView.topAnchor).isActive = true
picker.bottomAnchor.constraint(equalTo: pickerWrapperView.bottomAnchor).isActive = true

// Using wrapper view instead of picker
textField.inputView = pickerWrapperView