Arefly Arefly - 5 months ago 360
iOS Question

Add a Done button within a pop-up datePickerView in Swift?

I want to add a Done button within a popped up datePickerView in Swift.

Here is the code:

@IBOutlet var datePicker: UITextField!

@IBAction func dateTextInputPressed(sender: UITextField) {

var datePickerView : UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date

sender.inputView = datePickerView
datePickerView.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)
}

func handleDatePicker(sender: UIDatePicker) {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
datePicker.text = dateFormatter.stringFromDate(sender.date)
}


I can use this code to pop up a datePickerView successfully.

result of datePickerView

But the problem is after I've selected the date, it do not have a "Done" button so i cannot dismiss it.

So how can I add the Done button into it?

Thanks!

Answer

You can use a generic UIView for the inputView property of the UITextField. We can add the UIDatePicker and UIButton to this UIView.

@IBAction func dateTextInputPressed(sender: UITextField) {

    //Create the view
    let inputView = UIView(frame: CGRectMake(0, 0, self.view.frame.width, 240))


    var datePickerView  : UIDatePicker = UIDatePicker(frame: CGRectMake(0, 40, 0, 0))
    datePickerView.datePickerMode = UIDatePickerMode.Date
    inputView.addSubview(datePickerView) // add date picker to UIView

    let doneButton = UIButton(frame: CGRectMake((self.view.frame.size.width/2) - (100/2), 0, 100, 50))
    doneButton.setTitle("Done", forState: UIControlState.Normal)
    doneButton.setTitle("Done", forState: UIControlState.Highlighted)
    doneButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
    doneButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted)

    inputView.addSubview(doneButton) // add Button to UIView

    doneButton.addTarget(self, action: "doneButton:", forControlEvents: UIControlEvents.TouchUpInside) // set button click event

    sender.inputView = inputView
    datePickerView.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)

    handleDatePicker(datePickerView) // Set the date on start.
}

func handleDatePicker(sender: UIDatePicker) {
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    datePicker.text = dateFormatter.stringFromDate(sender.date)
}

func doneButton(sender:UIButton)
{
    datePicker.resignFirstResponder() // To resign the inputView on clicking done.
}