如何访问searchBar的明文按钮?

发布于 2024-10-05 18:01:38 字数 534 浏览 11 评论 0原文

当我点击 tableView 搜索上的“清除”按钮(编辑时出现的按钮)时,我试图让键盘消失。如何检测何时单击“清除”按钮,以便我可以退出firstResponder? 我已经在 textDidChange 方法中尝试过这个:

if (SearchBar.text == @"") {
    [SearchBar resignFirstResponder];
    NSLog(@"clear called");
}

这不起作用......并且也尝试过:

 if (SearchBar.text == nil) {
    [SearchBar resignFirstResponder];
    NSLog(@"clear called");
}

这两个方法都表明它们被调用。有什么想法吗?

编辑:现在resignFirstResponder似乎不起作用。键盘保留在屏幕上。我做错了什么?

When I hit the "clear" button (the one that appears when editing) on the tableView search, I was trying to get the keyboard to disappear. How can I detect when the "clear" button is clicked, so I can resign the firstResponder? I already tried this in the textDidChange method:

if (SearchBar.text == @"") {
    [SearchBar resignFirstResponder];
    NSLog(@"clear called");
}

which did not work...and also tried:

 if (SearchBar.text == nil) {
    [SearchBar resignFirstResponder];
    NSLog(@"clear called");
}

Neither methods show that they were called. Any ideas?

EDIT: Now resignFirstResponder does not seem to be working. The keyboard stays on screen. What's am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

猥︴琐丶欲为 2024-10-12 18:01:38

对于字符串比较,您应该使用

if([SearchBar.text isEqualToString: @""])

For string comparison you should use

if([SearchBar.text isEqualToString: @""])
梦中的蝴蝶 2024-10-12 18:01:38

您可以尝试通过注册 KVO 通知来观察搜索栏的 text 属性:

[self.searchBar addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:NULL];

然后实现:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  if (object == self.searchBar && [keyPath isEqualToString:@"text"]) {
    // Handle the new value of self.searchBar.text
  }
}

编辑:没关系,上面回答 =)

You can try watching the text property of the search bar by registering for a KVO notification:

[self.searchBar addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:NULL];

and then implementing:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  if (object == self.searchBar && [keyPath isEqualToString:@"text"]) {
    // Handle the new value of self.searchBar.text
  }
}

Edit: nevermind, answered above =)

酒废 2024-10-12 18:01:38

我知道这个问题很旧,但另一种方法是:

if(searchText.length == 0)

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString 中的 *)搜索文本

I know this question is old, but another way to do this is:

if(searchText.length == 0)

in - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文