Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add datepicker in UIActionsheet using Swift

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.

like image 749
Vijay Avatar asked Sep 11 '14 06:09

Vijay


2 Answers

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
    }
}
like image 112
karthikPrabhu Alagu Avatar answered Sep 27 '22 00:09

karthikPrabhu Alagu


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)
like image 36
Hardik Trivedi Avatar answered Sep 23 '22 00:09

Hardik Trivedi