Open UIDatePicker programmatically in iOS 14

后端 未结 9 1556
南笙
南笙 2020-12-23 16:46

I have this normal UIDatePicker (sorry that it\'s not in English, please ignore that):

\"my

9条回答
  •  猫巷女王i
    2020-12-23 17:33

    Define these variables

    var datePicker: UIDatePicker!
    var datePickerConstraints = [NSLayoutConstraint]()
    var blurEffectView: UIView!
    

    Then create a function showDatePicker() that you call to trigger the display of the UIDatePicker. First, create a subview with the same size of his parent View and give it a blur effect. Then add the UIDatePicker, as a subview on top of the blurred view.

       func showDatePicker() {
            datePicker = UIDatePicker()
            datePicker?.date = Date()
            datePicker?.locale = .current
            datePicker?.preferredDatePickerStyle = .inline
            datePicker?.addTarget(self, action: #selector(dateSet), for: .valueChanged)
            addDatePickerToSubview()
        }
    
        func addDatePickerToSubview() {
            guard let datePicker = datePicker else { return }
            // Give the background Blur Effect
            let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.regular)
            blurEffectView = UIVisualEffectView(effect: blurEffect)
            blurEffectView.frame = self.view.bounds
            blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            self.view.addSubview(blurEffectView)
            self.view.addSubview(datePicker)
            datePicker.translatesAutoresizingMaskIntoConstraints = false
            centerDatePicker()
            view.bringSubviewToFront(datePicker)
        }
    
        func centerDatePicker() {
            guard let datePicker = datePicker else { return }
            // Center the Date Picker
            datePickerConstraints.append(datePicker.centerYAnchor.constraint(equalTo: self.view.centerYAnchor))
            datePickerConstraints.append(datePicker.centerXAnchor.constraint(equalTo: self.view.centerXAnchor))
            NSLayoutConstraint.activate(datePickerConstraints)
        }
    

    And finally, once a date a selected in the UIDatePicker

     @objc func dateSet() {
            // Get the date from the Date Picker and put it in a Text Field
            compactDatePicker.date = datePicker.date
            blurEffectView.removeFromSuperview()
            datePicker.removeFromSuperview()
        }
    

    Not entirely sure about the blurr effect so hopefully someone can build on this solution.

提交回复
热议问题