Katie H
Katie H

Reputation: 2293

Dismissing keyboard on specific fields

I'm using this library in my Swift app to include a custom picker view rather than the default one: https://github.com/kirkbyo/Dropper

I have the library setup and working properly as it is intended to. On the same view that I am using this custom picker, I have a few text fields. When I add a function to dismiss the keyboard if the user clicks away from the keyboard, this library stops working properly, you cannot select any of the items in the drop down.

Here is what I have to dismiss the keyboard:

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)

func dismissKeyboard() {
    view.endEditing(true)
}

Upvotes: 0

Views: 80

Answers (2)

Rashwan L
Rashwan L

Reputation: 38833

First of all use textField.resignFirstResponder instead of view.endEditing(true) in the dismissKeyboard function. Regarding the problem with the selector in the library, try to add the the UITapGestureRecognizer to the entire view and if that don´t work try to add it to the dropdown view only.

Update

I downloaded the library and this worked for me, to hide the dropper on tap.

func dismissKeyboard(){
    if dropper.status != .Hidden {
       dropper.hideWithAnimation(0.1)
    }

    self.txtField.resignFirstResponder()
}

Update 2

The problem was that the UITapGesture was covering the entire view, so I added the delegate for the UITapGusture and added some exceptions.

So do this:
Add the UIGestureRecognizerDelegate in your class, so it looks like this:

class ViewController: UIViewController, UIGestureRecognizerDelegate

Add the delegate to your tap gesture

tap.delegate = self

And add this in your extension

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
    if touch.view!.isKindOfClass(UIButton) || touch.view!.isKindOfClass(UITableViewCell) || touch.view!.superview!.isKindOfClass(UITableViewCell) {
        return false
    }
    return true
}

And you should be good to go :)

Upvotes: 2

seto nugroho
seto nugroho

Reputation: 1379

Your gesture recognizer might interfere with your custom picker touch.

Try to identify that by tap and hold the custom picker selection for a few second, if it is working, then the gesture recognizer is surely interfere with your custom picker delegate function.

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,shouldReceiveTouch touch: UITouch) -> Bool
{
    if ([touch.view isDescendantOfView:yourCustomPickerView]) {
        return false
    }
    return true
}

Upvotes: 0

Related Questions