UISearchBar - 当点击取消按钮时,如何防止关闭 scopeBar?

Posted

技术标签:

【中文标题】UISearchBar - 当点击取消按钮时,如何防止关闭 scopeBar?【英文标题】:UISearchBar - How can I prevent dismissing the scopeBar when the cancel button is tapped? 【发布时间】:2011-07-21 17:22:55 【问题描述】:

我希望我的UISearchBar 的范围按钮始终可见,但即使我设置了searchBar.showsScopeBar = YES',如果我开始搜索然后取消它,按钮仍然会以动画形式消失。

当搜索被取消时,我有什么办法可以防止 scopeBar 被动画出来?

【问题讨论】:

【参考方案1】:

由于范围栏仅在UISearchController 处于活动状态时使用,所以我以不同的方式解决了这个问题。

我立即激活UISearchController

override func viewDidLayoutSubviews() 
    super.viewDidLayoutSubviews()
    // Immediately activating the searchController keeps scope bar permanently visible
    searchController.isActive = true
    // Tapping the cancel button triggers this method, which quickly toggles the scope bar
    // But the cancel button isn't needed anyway, so hiding it solves the problem
    searchController.searchBar.showsCancelButton = false

但现在UISearchController 始终处于活动状态,默认情况下UINavigationBar 是隐藏的,这可能不是您想要的。为了解决这个问题,我防止它被隐藏在viewDidLoad

searchController.hidesNavigationBarDuringPresentation = false

这种方法意味着我根本不需要使用showsScopeBar,因为它在UISearchController 处于活动状态时始终可见。

【讨论】:

【参考方案2】:

如果有人感兴趣,下面的委托方法可以做到。

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar

    [searchBar setShowsScopeBar:YES];
    return YES;

【讨论】:

以上是关于UISearchBar - 当点击取消按钮时,如何防止关闭 scopeBar?的主要内容,如果未能解决你的问题,请参考以下文章