Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a UIDatePicker instead of Keyboard for UITextField Issues

Hi I am trying to display a UIDatePicker instead of a keyboard whenever a UITextField is tapped so that the user can give a start and end time for an event. My code works but not well and not the way I want it to.

My first issue is that whenever you tap on one of the UITextField the UIDatePicker only come up the second time the UITextField is tapped. Otherwise it shows the original keyboard.

My second issue is that whenever the UIDatePicker is edited it only changes the UITextField whenever the UIDatePicker is edited. I need the UITextField to display the string in the UIDatePicker as soon as its opened so that the UITextField is up to date with what is going on the UIDatePicker.

Here is my current code:

override func viewDidLoad() {
super.viewDidLoad()
 var datePickerView  : UIDatePicker = UIDatePicker()
    datePickerView.datePickerMode = UIDatePickerMode.Time
    StartTimeTextField.inputView = datePickerView
    datePickerView.addTarget(self, action:
    Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)

    var datePickerView2  : UIDatePicker = UIDatePicker()
    datePickerView2.datePickerMode = UIDatePickerMode.Time
    EndTimeTextField.inputView = datePickerView2
    datePickerView2.addTarget(self, action: Selector("handleDatePicker2:"), forControlEvents: UIControlEvents.ValueChanged)
    }

func handleDatePicker(sender: UIDatePicker) {
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "hh mm am pm"
    StartTimeTextField.text = dateFormatter.stringFromDate(sender.date)
}



func handleDatePicker2(sender: UIDatePicker) {
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "hh mm am pm"
    EndTimeTextField.text = dateFormatter.stringFromDate(sender.date)
}

Can anyone help me? Thanks

like image 305
Trip Phillips Avatar asked Aug 22 '15 06:08

Trip Phillips


1 Answers

Why you are changing keyboard by the action!

Just add your code in viewDidLoad :

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

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

and remove that methods like

@IBAction func
like image 50
Ashish Kakkad Avatar answered Nov 19 '22 21:11

Ashish Kakkad