Tommy K
Tommy K

Reputation: 1807

dismissing iOS keyboard on tap without breaking table view cell tap functionality

I want to add functionality to dismiss the keyboard on UITextFields and UITextViews when the users taps outside the keyboard. I have a view very similar to New Event in iOS Calendar thats a bunch of static table cells, some of which have text fields and some send to a Show view (like the "Repeat" cell in the New Event in the Calendar app).

I tried using the following:

override func viewDidLoad() {
    super.viewDidLoad()

    //Looks for single or multiple taps. 
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
    view.addGestureRecognizer(tap)
}

//Calls this function when the tap is recognized.
func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
}

but this breaks the functionality of the cells that tap to segue to a Show. I can get around this by just having the keyboard go down on "return", but I can't do this with my UITextView since that adds a newline. The Calendar app dismisses the keyboard in the UITextView on what seems to be a swipe up and down, but I'm not sure how to add this functionality myself as I'm new to iOS programming.

Any solutions for getting around this problem?

Upvotes: 1

Views: 580

Answers (3)

Mahendra
Mahendra

Reputation: 8904

Another solution is that you can add UITapGestureRecognizer on view, and when a view is tapped then dismiss keyboard just like below.

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[self.view addGestureRecognizer:tapGesture];

-(void)handleTap:(UITapGestureRecognizer *)sender {
    //do stuff
}

Upvotes: 0

rmickeyd
rmickeyd

Reputation: 1551

Select your tableView in storyboards. Then in attributes inspector find keyboard and set to "Dismiss Interactively." This should allow for the swipe down to dismiss.

Upvotes: 2

matt
matt

Reputation: 534893

The Calendar app dismisses the keyboard in the UITextView on what seems to be a swipe up and down

Indeed it does. And that is what you should do. A text view and a table view are both scroll views. The usual solution, therefore, is to set the scroll view's keyboardDismissMode to .Interactive or .OnDrag. That is how the Calendar does it, and that's how you should do it.

Upvotes: 1

Related Questions