问题
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
回答1:
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
}
回答2:
Adding tableView.keyboardDismissMode = .onDrag to viewDidLoad() worked like a charm.
回答3:
(As hinted at in the self-answering comment) If you want to get table search behavior like the built-in contacts app, you can't just slap a UISearchBar into a view with a UITableView, instead you need to use a UITableViewController together with a Search Display Controller. This sample app is a perfect guide:
https://developer.apple.com/library/ios/#samplecode/TableSearch/Introduction/Intro.html
来源:https://stackoverflow.com/questions/3006005/dismissing-the-keyboard-with-uisearchbar-without-resigning-first-responder