首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在UISearchBar中启用取消按钮?

如何在UISearchBar中启用取消按钮?
EN

Stack Overflow用户
提问于 2012-04-02 05:42:33
回答 18查看 28.2K关注 0票数 51

在iPhone上的联系人应用程序中,如果你输入一个搜索词,然后点击“搜索”按钮,键盘将隐藏,但取消按钮仍可用。在我的应用程序中,当我调用resignFirstResponder时,取消按钮被禁用。

有人知道如何在保持取消按钮处于启用状态的同时隐藏键盘吗?

我使用以下代码:

代码语言:javascript
复制
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

键盘滑出视线,但搜索文本字段右侧的" cancel“按钮被禁用,因此我无法取消搜索。联系人应用程序将“取消”按钮保持在启用状态。

我认为一种解决方案可能是深入研究searchBar对象并对实际的文本字段调用resignFirstResponder,而不是搜索栏本身。

感谢您提供的任何意见。

EN

回答 18

Stack Overflow用户

回答已采纳

发布于 2012-04-02 06:33:56

尝尝这个

代码语言:javascript
复制
for(id subview in [yourSearchBar subviews])
{
    if ([subview isKindOfClass:[UIButton class]]) {
        [subview setEnabled:YES];
    }
}
票数 22
EN

Stack Overflow用户

发布于 2013-08-09 23:53:47

这种方法在iOS7中有效。

代码语言:javascript
复制
- (void)enableCancelButton:(UISearchBar *)searchBar
{
    for (UIView *view in searchBar.subviews)
    {
        for (id subview in view.subviews)
        {
            if ( [subview isKindOfClass:[UIButton class]] )
            {
                [subview setEnabled:YES];
                NSLog(@"enableCancelButton");
                return;
            }
        }
    }
}

(还要确保在使用_searchBar resignFirstResponder之后在任何地方调用它。)

票数 29
EN

Stack Overflow用户

发布于 2012-09-13 20:21:14

当您开始滚动表格而不是点击“搜索”按钮时,接受的解决方案将不起作用。在这种情况下,“取消”按钮将被禁用。

这是我的解决方案,每次使用KVO禁用"Cancel“按钮时都会重新启用该按钮。

代码语言:javascript
复制
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    // Search for Cancel button in searchbar, enable it and add key-value observer.
    for (id subview in [self.searchBar subviews]) {
        if ([subview isKindOfClass:[UIButton class]]) {
            [subview setEnabled:YES];
            [subview addObserver:self forKeyPath:@"enabled" options:NSKeyValueObservingOptionNew context:nil];
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    // Remove observer for the Cancel button in searchBar.
    for (id subview in [self.searchBar subviews]) {
        if ([subview isKindOfClass:[UIButton class]])
            [subview removeObserver:self forKeyPath:@"enabled"];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    // Re-enable the Cancel button in searchBar.
    if ([object isKindOfClass:[UIButton class]] && [keyPath isEqualToString:@"enabled"]) {
        UIButton *button = object;
        if (!button.enabled)
            button.enabled = YES;
    }
}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9968595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档