Reputation: 3789
So I am using a UIPickerView as the first responder of a UITextField. I set this as shows:
var myPickerView = UIPickerView()
myTextField.inputView = myPickerView
I was not having issues with this until I added a UITapGestureRecognizer (that would allow me to click outside of the picker view to dismiss it) to the view like so:
let dismissUnitPickerGesture = UITapGestureRecognizer(target: self, action: "hidePicker")
dismissUnitPickerGesture.delegate = self
dismissUnitPickerGesture.cancelsTouchesInView = false
hidePicker func:
@IBAction func hidePicker(){
myTextField.resignFirstResponder()
//I don't think this code is relevant to the problem, but I included it just in case
if materialSelectedOption == "Aluminum Cans" {
amountTextField.placeholder = "Number of Cans"
unitCell.hidden = true
}
}
Now it takes up to five clicks on the UITextField on the simulator to open the picker view, which is frustrating and obviously not good for an app. I'm pretty sure it has something to do with the tap gesture, but I could be wrong.
If there are any other questions you guys have please let me know.
Upvotes: 0
Views: 82
Reputation: 3906
I Suggest you to add tool bar with "Done" and "Clear" items instead gesture. The following code you can use:
func textFieldDidBeginEditing(sender: UITextField) {{
let toolBar = UIToolbar(frame: CGRectMake(0, self.myTextField.frame.size.height/6, self.myTextField.frame.size.width, 40.0))
toolBar.layer.position = CGPoint(x: self.myTextField.frame.size.width/2, y: self.myTextField.frame.size.height-20.0)
toolBar.barStyle = UIBarStyle.BlackTranslucent
toolBar.tintColor = UIColor.whiteColor()
let defaultButton = UIBarButtonItem(title: "Clear", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(CustomTimePickerTextView.clearTime(_:)))
let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(CustomTimePickerTextView.donePressed(_:)))
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
let textButton = UIBarButtonItem(title: self.placeholder, style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
toolBar.setItems([defaultButton,flexSpace,textButton,flexSpace,doneButton], animated: true)
self.myTextField.inputAccessoryView = toolBar
}
func clearTime(sender:UIBarButtonItem) {
//
}
func donePressed(sender: UIBarButtonItem) {
self.myTextField.resignFirstResponder()
}
Upvotes: 0
Reputation: 1222
adding a UITapGestureRecognizer
to just detect that a tap is registered outside the pickerView and hide it is kind of wrong!
you can use the touchesBegan
function and call self.view.endEditing(true)
like so:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
//or use textField.endEditing(true)
}
Upvotes: 0