简体   繁体   中英

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

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.

    }

}

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.

You can also just create an outlet for the datePicker. @IBOutlet weak var datePicker: UIPickerView!

then in your function

@IBAction func DoneButton(sender: UIButton) {

    datePicker.hidden = true
}

You could try something as gestureRecognizer to make the UIDatePicker disappear:

@objc func viewTapped(gestureRecognizer: UITapGestureRecognizer) {
   view.endEditing(true)    
}

This is what I used in my app so when the user taps on anywhere on the screen the UIDatePicker goes away!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM