Add datepicker in UIActionsheet using Swift

10,057

Solution 1

It is not possible, but you can use a UItextfield input view and accessory view to show and dismiss a datepicker when the user clicks the textfield

class KPDatePickerViewController: UIViewController {
    var datePicker:UIDatePicker!
    @IBOutlet var dateTextField:UITextField!

    override func viewDidLoad() {
        var customView:UIView = UIView (frame: CGRectMake(0, 100, 320, 160))
        customView.backgroundColor = UIColor.brownColor()
        datePicker = UIDatePicker(frame: CGRectMake(0, 0, 320, 160))
        customView .addSubview(datePicker)
        dateTextField.inputView = customView
        var doneButton:UIButton = UIButton (frame: CGRectMake(100, 100, 100, 44))
        doneButton.setTitle("Done", forState: UIControlState.Normal)
        doneButton.addTarget(self, action: "datePickerSelected", forControlEvents: UIControlEvents.TouchUpInside)
        doneButton.backgroundColor = UIColor .blueColor()
        dateTextField.inputAccessoryView = doneButton
    }

    func datePickerSelected() {
        dateTextField.text =  datePicker.date.description
    }
}

Solution 2

Yes it is definitely possible to present UIDatePicker in UIAlertController. Check out the following code in Swift 4. I have used this code many a times in Projects and it worked fine.

let dateChooserAlert = UIAlertController(title: "Choose date...", message: nil, preferredStyle: .actionSheet)
dateChooserAlert.view.addSubview(datePicker)
dateChooserAlert.addAction(UIAlertAction(title: "Done", style: .cancel, handler: { action in
        // Your actions here if "Done" clicked...
    }))
let height: NSLayoutConstraint = NSLayoutConstraint(item: dateChooserAlert.view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.1, constant: 300)
dateChooserAlert.view.addConstraint(height)
self.present(dateChooserAlert, animated: true, completion: nil)
Share:
10,057
Vijay
Author by

Vijay

I am an iOS developer and always had a keen interest in learning new technology.

Updated on June 05, 2022

Comments

  • Vijay
    Vijay about 2 years

    Is there any way to present the datepicker from UIAlertControllerStyle.ActionSheet ? There is way to add buttons and add actions to those buttons in the ActionSheet, but i couldn't find a solution to add a datepicker or any custom view in the ActionSheet.