Search code examples
iosswiftxcodeuidatepickerxcode12

UIDatePicker width is not going to set properly by using Xcode 12.4


I create date picker by using code. Date picker frame is set properly while application compile by using Xcode 11.6 but when application compile using Xcode 12.2 or above then Date picker width causes problem Check this image.

        let screenWidth = self.view.frame.width
        let screenHeight = self.view.frame.height

        datePicker = UIDatePicker(frame: CGRect(x: 0, y: screenHeight - 216 - 44, width: screenWidth, height: 216))
        if #available(iOS 13.4, *) {
            datePicker.frame = CGRect(x: 0, y: screenHeight - 216 - 44, width: screenWidth, height: 216)
            datePicker.preferredDatePickerStyle = .wheels
        }
        datePicker.datePickerMode = .date
        datePicker.minimumDate = getTwoWeekOldDateFormCurrentDate()
        datePicker.backgroundColor = UIColor.white
        datePicker.setValue(UIColor.black, forKeyPath: "textColor")
        self.view.addSubview(datePicker)

I know, I am adding two time frame method in code, it will use for iOS 13.4 and above.


Solution

  • Add the following code in your viewController.

    override func viewDidLayoutSubviews() {
        let screenWidth = self.view.frame.width
        let screenHeight = self.view.frame.height
        datePicker.frame = CGRect(x: 0, y: screenHeight - 216 - 44, width: screenWidth, height: 216)
    }