iOS 13中使用navigationItem.searchController导航栏变白且搜索框无法收起问题
首先明确:这不是iOS13的bug,而是苹果在iOS13中更新了导航栏的外观管理和搜索栏的滚动触发逻辑,针对你的两个问题,分别给出解决方案:
一、恢复导航栏半透明效果与自定义颜色
你之前用configureWithOpaqueBackground()会强制导航栏变为不透明,这就是为什么你只能用调整后的纯色来模拟半透明效果。正确的做法是使用半透明的外观配置,同时匹配iOS13+的新API:
修改AppDelegate中的iOS13配置代码如下:
if #available(iOS 13.0, *) { let appearance = UINavigationBarAppearance() // 使用默认的半透明背景配置,而非不透明 appearance.configureWithDefaultBackground() // 设置带透明度的背景色,保留半透明效果 appearance.backgroundColor = UIColor.red.withAlphaComponent(0.8) // 配置标题文字颜色 appearance.titleTextAttributes = [.foregroundColor: UIColor.white] appearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white] // 同时设置standard和scrollEdgeAppearance,确保滚动前后颜色一致 UINavigationBar.appearance().standardAppearance = appearance UINavigationBar.appearance().scrollEdgeAppearance = appearance // 显式开启半透明(配合appearance配置生效) UINavigationBar.appearance().isTranslucent = true } else { UINavigationBar.appearance().tintColor = .white UINavigationBar.appearance().barTintColor = .red UINavigationBar.appearance().isTranslucent = true }
这样就能让导航栏回到iOS13之前的半透明效果,同时保留自定义的红色背景和白色文字。
二、解决搜索栏无法收起的问题
这个问题的核心原因是:iOS13中,只有当tableView的内容足够多、能产生有效滚动时,系统才会触发搜索栏的收起逻辑。当内容不足时,即使你滚动tableView,也不会触发收起行为。
有两个简单的解决办法:
方案1:强制tableView支持垂直反弹(推荐)
即使tableView内容不足,也允许用户向上滚动,从而触发搜索栏收起。在你的ViewController的viewDidLoad中添加一行代码:
override func viewDidLoad() { super.viewDidLoad() let searchController = UISearchController(searchResultsController: nil) navigationItem.searchController = searchController // 强制开启垂直反弹 tableView.alwaysBounceVertical = true // 显式确认搜索栏随滚动隐藏(默认是true,显式设置更稳妥) navigationItem.hidesSearchBarWhenScrolling = true }
这个方案完全贴合系统的交互逻辑,体验最自然。
方案2:手动控制搜索栏收起
如果方案1不符合你的需求,可以在tableView滚动时手动触发搜索栏收起。比如在scrollViewDidScroll代理方法中判断滚动方向,手动关闭搜索控制器:
override func scrollViewDidScroll(_ scrollView: UIScrollView) { // 当用户向上滚动超过一定偏移量时,关闭搜索控制器 if scrollView.contentOffset.y > 50 && navigationItem.searchController?.isActive == true { navigationItem.searchController?.isActive = false } }
不过这个方案需要自己调整触发阈值,体验不如方案1顺滑,建议优先用方案1。
内容的提问来源于stack exchange,提问作者Jay Lee
相关产品推荐
相关产品推荐

