ios - 如何正确隐藏范围按钮

标签 ios swift uisearchbar ios12

初始状态:

Initial state

sb.showsScopeBar 设置为 false

searchBarShouldBeginEditing 使范围按钮在搜索栏被激活时出现:

func searchBarShouldBeginEditing(_ sb: UISearchBar) -> Bool {
        sb.setShowsCancelButton(true, animated: true)
        sb.scopeButtonTitles = scopeButtonTitles
}

enter image description here

点击取消按钮,正确隐藏范围按钮,我们回到原始状态。

注意这是默认行为,我们的 searchBarCancelButtonClicked 除了在必要时恢复以前的查询文本外没有做任何事情。

Initial state

现在烦人的事情来了......

如果我放

sb.setShowsCancelButton(false, animated: true)

在 searchBarShouldEndEditing 或 searchBarTextDidEndEditing 中,取消按钮消失但范围按钮缩小:

enter image description here

添加 sb.scopeButtonTitles = nil 使范围按钮消失,但搜索栏不会调整大小:

enter image description here

调用 sb.sizeToFit() 似乎根本没有帮助...使用 sb.showsScopeBar 完全破坏了搜索栏 UI。

最佳答案

找到解决办法了!

要模拟按下取消按钮的行为(隐藏范围按钮并调整搜索栏的大小):

func searchBarTextDidEndEditing(_ sb: UISearchBar) {
    sb.setShowsCancelButton(false, animated: true)
    searchController?.isActive = false
}

我们不需要将 sb.scopeButtonTitles 设置为 nil。

关于ios - 如何正确隐藏范围按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52701156/

相关文章:

ios - 隐藏 UIToolBar 和 UINavigation 并展开 UIWebView? - iOS

objective-c - 仅在可用时导入类(例如 UIPopOverControllerDelegate 仅在 >= 3.2 上)

ios - 如何使用 Swift 4 从 JSON 获取特定值?

ios - 为其轮廓创建 Box 后 UITextView 的大小和位置错误

swift - 参数标签 '(content:)' 与任何可用的重载、swift、vapor、rest invapor、使用 postgresql 都不匹配

ios - 在 AppDelegate 中自定义 UISearchBar 和 UINavigationBar 的外观?为什么要在类而不是实例级别进行定制?

ios - 使用 UISearchBar 后返回复选标记 - Swift

ios - iOS 中的用户对象位置 (swift)

ios - UINavigationController inside UITabBarController inside UISplitViewController(仍然)以模态方式显示细节 Controller 而不是推送

ios - 如何在 Xcode 中增加范围标题和搜索栏的字体大小?