[英]iPhone perform action when UITextField / UISearchBar's clear button is pressed
Is it possible to gain access to a delegate method that will allow additional actions to be performed when the "clear" button is pressed on a UITextField / UISearchBar? 是否可以访问委托方法,以便在UITextField / UISearchBar上按下“清除”按钮时执行其他操作?
Thanks 谢谢
See: UITextFieldDelegate Protocol Reference 请参阅: UITextFieldDelegate协议参考
If you set your view controller as the delegate for your text field (can be done in interface builder), you can use: 如果将视图控制器设置为文本字段的委托(可以在界面构建器中完成),则可以使用:
- (void)clearSearchTextField
{
...
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
if (textField == self.searchTextField) [self clearSearchTextField];
return YES;
}
For Swift 3: 对于Swift 3:
To perform an action when the "clear" button is pressed on a UITextField 在UITextField上按下“清除”按钮时执行操作
func textFieldShouldClear(_ textField: UITextField) -> Bool {
if textField == yourTextFieldName {
// do some action
}
return true
}
For a UISearchBar
you will want to implement func searchBar(searchBar: UISearchBar, textDidChange searchText: String)
. 对于UISearchBar
您需要实现func searchBar(searchBar: UISearchBar, textDidChange searchText: String)
。
This is triggered before func searchBarTextDidBeginEditing(searchBar: UISearchBar)
and before func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool
as well. 这是在func searchBarTextDidBeginEditing(searchBar: UISearchBar)
之前和func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool
之前触发的func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool
也是如此。
You implementation should look something like this: 您的实现应该看起来像这样:
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchText == "" {
//Code to execute when search is cleared
}
}
When you clear the text field several events will happen that you will have access to through either the UISearchDisplayDelegate or the UISearchBarDelegate such as searchBar:textDidChange
and searchDisplayController:shouldReloadTableForSearchString
清除文本字段时,将发生几个事件,您可以通过UISearchDisplayDelegate或UISearchBarDelegate访问,例如searchBar:textDidChange
和searchDisplayController:shouldReloadTableForSearchString
This will also cause the search table to hide so it will trigger 这也会导致搜索表隐藏,因此会触发
searchDisplayController:willHideSearchResultsTableView
searchDisplayController:didHideSearchResultsTableView
When the search table will hide you can check if the search text is empty and then do whatever you need to do. 当搜索表隐藏时,您可以检查搜索文本是否为空,然后执行您需要执行的操作。
请参阅我的回答: https ://stackoverflow.com/a/3852509/91458 - 它适用于searchBar,但也应该应用于textField。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.