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

NavigationStack中SearchBar背景色与设置不符的问题及临时解法

我尝试在NavigationStack中配置SearchBar的颜色,代码如下:

NavigationStack {
   ...
}.searchable(text: $events.searchText, isPresented: $searchIsActive)

默认显示效果:搜索栏带有系统默认的浅灰色背景。

当我通过以下代码设置背景色时:

UISearchTextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = UIColor.white

实际显示的搜索栏颜色为#DEDEE1;若设置为黑色,实际颜色则是#1C1C1F——看起来存在某种需要移除的「色调叠加」效果。

更新1

通过视图层级调试器排查发现,_UISearchBarSearchFieldBackgroundView是问题根源,它的背景应用了tertiarySystemFillColor,但我不知道该如何消除这个效果。

更新2

我找到了一个临时解决方案(不算标准实现):虽然通过UISearchTextField.appearance(...)设置背景色后,tertiarySystemFillColor的效果依然存在,但借助introspect可以解决问题:

SomeView {
}.introspect(.searchField , on: .iOS(.v17)) { searchField in
  // 设置背景色
  searchField.searchTextField.backgroundColor = .white

  // 移除边框样式会同时消除`tertiarySystemFillColor`效果
  searchField.searchTextField.borderStyle = .none

  // 移除边框会清除圆角,因此需要重新设置
  searchField.searchTextField.layer.cornerRadius = 10
}

这个方法解决了我的问题。我之前尝试通过全局外观配置实现,但并未生效:

UISearchTextField.appearance().borderStyle = .none
UISearchTextField.appearance().layer.cornerRadius = 10

再次查看视图层级调试器,之前的额外图层已被移除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:59:51