如果我将resign代码放在我的if条件下键盘不会退出,如果我评论if条件我的键盘辞职。
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if (searchText.length == 0) {
[searchBar resignFirstResponder];
}
}
我想在用户按下“x”按钮时退出键盘,即UISearchBar文本为空时。有没有办法做到这一点?
答案 0 :(得分:10)
只是辞职第一个响应者,但是在下一个运行循环中这样:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if ([searchText length] == 0)
{
[searchBar performSelector:@selector(resignFirstResponder)
withObject:nil
afterDelay:0];
}
}
经过测试,确实有效。
答案 1 :(得分:3)
针对switf 3进行了更新:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == ""
{
searchBar.perform(#selector(self.resignFirstResponder), with: nil, afterDelay: 0.1)
}
}
答案 2 :(得分:1)
添加“取消按钮”以查看加载和添加方法-> searchBarCancelButtonClicked
searchBar.showsCancelButton = true
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
答案 3 :(得分:0)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSRange foundRange = [searchText rangeOfString:@"x"];
if (foundRange.location != NSNotFound) {
if (searchText.length == 0) {
[searchBar resignFirstResponder];
}
}
}