在 iOS 15 上的 SwiftUI 中使用新的
.searchable()
修饰符时,我无法自定义搜索栏外观。具体来说,我不希望它与我用于导航栏的颜色看起来很好。
我尝试像这样改变
.appearance()
。
UISearchBar.appearance().backgroundColor = UIColor.white
UISearchBar.appearance().tintColor = UIColor.white
UISearchBar.appearance().barTintColor = UIColor.white
但只得到了这个。
尽管这种方法很成功,但间距看起来不太好。我宁愿把它染成白色。
在
.font
之后设置 .foregroundColor
和 .searchable
修饰符将获得所需的结果,但在撰写本文时仍然无法与 .background
修饰符一起使用(iOS 16)。
不理想,但您可以尝试仅将搜索栏的配色方案/界面样式覆盖为深色:
UISearchBar.appearance().overrideUserInterfaceStyle = .dark
这样,导航栏和应用程序的其余部分应该不受影响。
iOS 16,我这样做了:
UISearchBar.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).setImage(<your search image, e.g., magnifyingGlassImage>, for: .search, state: .normal)
UISearchBar.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).setImage(<your clear image, e.g., closeImage>, for: .clear, state: .normal)
UISearchBar.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).tintColor = <Color.yourTintColor>
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = <Color.yourBackgroundColor>
UISearchTextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: <your promptText, e.g., "Search", attributes: [.foregroundColor: <Color.yourForegroundColor>])
通过更改应用了
.preferredColorScheme()
修改器的视图的 .searchable
,可以将输入字段的文本颜色从黑色更改为白色。设置 .preferredColorScheme(.dark)
会将颜色设置为白色。