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)scrollView开发者_运维知识库DidScroll:(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
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
}
Adding tableView.keyboardDismissMode = .onDrag
to viewDidLoad()
worked like a charm.
(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
I tried multiple options but all the desired output is not achieved, like hiding the cancel along with keyboard.
So I used searchBar.inputAccessoryView
which will be visible above the keyboard with a button at right (toolbar).
class AnyViewClass{
func createSearch(){
searchBar.inputAccessoryView = ViewsFactory.createAccessoryView(withButtonType:.done,target: self, action:#selector(YourClass.keyboardDonePressed))
}
@objc private func keyboardDonePressed(){
searchBar?.resignFirstResponder()
searchBar?.text = nil
}
}
class ViewsFactory {
class func createAccessoryView(withButtonType type:UIBarButtonItem.SystemItem,
target: Any?,
action: Selector?) -> UIToolbar{
var accessoryDoneButton: UIBarButtonItem!
let accessoryToolBar = UIToolbar(frame: CGRect(x: 0,
y: 0,
width: UIScreen.main.bounds.width,
height: 44))
let emptySpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
target: nil,
action: nil)
accessoryDoneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done,
target: target,
action: action)
accessoryDoneButton.tintColor = <any color>
accessoryToolBar.items = [emptySpace, accessoryDoneButton]
return accessoryToolBar
}
}
精彩评论