Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UIDatePicker for text field input - how to make UIDatePicker disappear?

Tags:

ios

swift

This is my first ever attempt at Swift or an iPhone app, so needless to say I'm not sure how to do many things at this point.

Right now I have a view controller with a text field and a button. I've managed to find example code to almost accomplish what I need. I'd like to do the following:

  1. When I click into the text field have a UIDatePicker come on screen.
  2. Set the UIDate picker to display time only - not a date.
  3. Put the selected UIDatePicker time in the textfield.
  4. Have the UIDatePicker go away when I click on the button.

1 through 3 is working. But I can't figure out how to have the UIDatePicker go away and still come back on the screen if I click into the text field again.

import UIKit

class ViewController: UIViewController {


    @IBOutlet weak var dateField: UITextField!

    @IBAction func dateField(sender: UITextField) {

        var datePickerView  : UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.Time
        sender.inputView = datePickerView
        datePickerView.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)

    }
    @IBAction func DoneButton(sender: UIButton) {

        //How to make datepicker disappear???
    }

    func handleDatePicker(sender: UIDatePicker) {
        var timeFormatter = NSDateFormatter()
        timeFormatter.dateStyle = .NoStyle
        timeFormatter.timeStyle = .ShortStyle
        dateField.text = timeFormatter.stringFromDate(sender.date)
    }

    override func viewDidLoad() {
     super.viewDidLoad()
     // Do any additional setup after loading the view, typically from a nib.

    }

}
like image 905
MGann Avatar asked Nov 18 '14 02:11

MGann


1 Answers

You call resignFirstResponder on the text field:

@IBAction func DoneButton(sender: UIButton) {
    dateField.resignFirstResponder()
}

Also, it's not a great idea to have a method and a property with the same name - not sure about precedence there, but chances are it could be confusing at some point.

like image 178
Nate Cook Avatar answered Sep 28 '22 22:09

Nate Cook