如何修改NavigationStack中.searchable()的取消按钮颜色?
方案1:精准定位UISearchBar内的UIBarButtonItem(iOS15+通用)
直接通过UIAppearance API,只修改搜索栏包含的取消按钮样式,不会影响其他导航栏按钮,是最可靠的方案:
@main struct YourApp: App { init() { // 定位UISearchBar中的取消按钮 let searchCancelButton = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]) searchCancelButton.tintColor = .systemOrange // 替换为你的App配色 } var body: some Scene { WindowGroup { NavigationStack { // 你的页面内容 } } } }
原理:搜索栏的取消按钮本质是UIBarButtonItem,通过whenContainedInInstancesOf限定作用范围,避免全局样式污染。
方案2:在NavigationStack层级设置tint颜色(iOS16+)
取消按钮属于导航栏的一部分,会继承NavigationStack的tint属性,把tint()修饰符加在NavigationStack层级而非.searchable()之后:
NavigationStack { // 页面内容 } .searchable(text: $searchText) .tint(.yourCustomColor)
如果App有明暗主题区分,可以结合动态颜色适配:
NavigationStack { // 页面内容 } .searchable(text: $searchText) .tint(Color(uiColor: UIColor { traitCollection in traitCollection.userInterfaceStyle == .dark ? .white : .black }))
方案3:iOS17+专属:结合toolbarColorScheme强制样式
iOS17新增toolbarColorScheme修饰符,可单独给导航栏指定配色方案,配合tint使用能确保取消按钮颜色跟随设置:
NavigationStack { // 页面内容 } .searchable(text: $searchText) .toolbarColorScheme(.dark, for: .navigationBar) .tint(.white)
这个方法适合需要强制搜索栏区域使用某一主题样式的场景。
内容的提问来源于stack exchange,提问作者lagoupo
相关产品推荐
相关产品推荐

