Search code examples
iosswiftlayoutuidatepicker

iOS14 UIDatePicker has an offset


Adding a UIDatePicker and running it on iPhone SE2 or iPhone 8, has an offset on the right side.

This is the code used to add the UIDatePicker

override func viewDidLoad() {
    super.viewDidLoad()
    let datePicker = UIDatePicker()
    datePicker.datePickerMode = .date
    datePicker.preferredDatePickerStyle = UIDatePickerStyle.inline
    datePicker.backgroundColor = .red
    view.addSubview(datePicker)
    datePicker.translatesAutoresizingMaskIntoConstraints = false
}

And This iOS how it looks on iPhone SE2 and iPhone 11 (notice the cutoff on the right side of the iPhone SE2)

enter image description here

Anyone have this issue? any fix?


Solution

  • You should be able to solve that by adding layout anchors to the leading and trailing of your date picker:

        datePicker.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(datePicker)
    
        datePicker.topAnchor.constraint(equalTo: view.topAnchor,
                                        constant: 0).isActive=true
        datePicker.leadingAnchor.constraint(equalTo: view.leadingAnchor,
                                            constant: 0).isActive=true
        datePicker.trailingAnchor.constraint(equalTo: view.trailingAnchor,
                                             constant: 0).isActive=true