Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismissing the keyboard with UISearchBar, without resigning first responder

Hey, I was working on a navigation-based app on iPhone similar to the contacts app. When you input something in the search bar, and scroll in the table (in the contacts app), the keyboard goes away. I don't think it resigns first responder though, because when I try and do that in -(void)scrollViewDidScroll:(UIScrollView *)scrollView, it disables the cancel button, which does not happen in the contacts app. Basically my question is how do I dismiss the keyboard without disabling the cancel button, like in the contacts app?

Thanks

like image 755
Mike Avatar asked Jun 09 '10 13:06

Mike


2 Answers

Well, just ran into this very old question. You can enable the 'cancel' button when you start to scroll as follows:

func scrollViewWillBeginDragging(scrollView: UIScrollView) {
    searchBar.resignFirstResponder()
    let searchCancelButton = searchBar.valueForKey("cancelButton") as! UIButton
    searchCancelButton.enabled = true // <-- THIS line is the trick

}

Swift 4

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    searchBar.resignFirstResponder()
    let cancelButton = searchBar.value(forKey: "cancelButton") as! UIButton
    cancelButton.isEnabled = true
}
like image 117
sweepez Avatar answered Oct 31 '22 16:10

sweepez


Adding tableView.keyboardDismissMode = .onDrag to viewDidLoad() worked like a charm.

like image 35
Norman Avatar answered Oct 31 '22 15:10

Norman