You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何激活代码添加的UISearchBar后导航栏被推出视图?

解决UISearchBar激活时导航栏被推出视图的问题

我来帮你搞定这个导航栏被顶出去的问题~ 当把UISearchBar作为tableView的表头视图时,激活搜索栏导致导航栏异常,通常是UISearchController的导航栏相关配置没设置到位,结合你的代码给你几个针对性方案:

方案1:禁用搜索控制器的导航栏隐藏功能

这是最直接的解决办法,默认情况下UISearchController会在激活时隐藏导航栏,咱们手动把这个行为关掉就行,在你的代码里添加一行:

searchController.hidesNavigationBarDuringPresentation = false

把这行放在你设置obscuresBackgroundDuringPresentation的代码后面,就能强制保留导航栏。

方案2:检查导航栏半透明属性

如果你的导航栏是半透明状态,可能会和tableView的偏移设置冲突,你可以尝试关闭半透明:

navigationController?.navigationBar.isTranslucent = false

不过这个方案要结合你的页面布局来调整,如果方案1生效就优先用方案1。

方案3:调整tableView的偏移设置

你当前代码里设置了tableView的contentOffset,把搜索栏顶到导航栏下方:

tableView.setContentOffset(CGPoint(x: 0.0, y: (self.tableView.tableHeaderView?.frame.size.height)!), animated: false)

这个操作可能会让系统在激活搜索栏时误判布局,你可以先注释掉这行代码测试一下,如果是这个原因导致的,再重新调整偏移量适配导航栏高度。

调整后的完整代码示例

把方案1的配置加进去,你的代码会变成这样:

// 配置搜索控制器核心属性
searchController.searchBar.delegate = self
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false // 新增关键配置
searchController.searchBar.placeholder = "Suche nach Plan"

// 页面基础配置
navigationItem.title = navigationItem.title ?? ci("plan_p")
tableView.rowHeight = 100.0
tableView.tableHeaderView = searchController.searchBar
// 可先注释下面这行测试导航栏问题
// tableView.setContentOffset(CGPoint(x: 0.0, y: (self.tableView.tableHeaderView?.frame.size.height)!), animated: false)

definesPresentationContext = true

guard let projectId = GlobalState.selectedProjectId, let byProject : Results<Structure> = self.by(projectId: projectId) else { return }

先试试方案1,基本能解决大部分这类问题,如果还有异常再依次尝试方案2和3。

内容的提问来源于stack exchange,提问作者user11080824

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:59:24