自定义可搜索的 SwiftUI iOS 15 搜索栏

7
使用iOS 15 SwiftUI中的新的.searchable()修饰符时,我无法自定义搜索栏的外观。具体而言,我希望它能够与我用于导航栏的颜色匹配。enter image description here 我尝试像这样修改.appearance()
UISearchBar.appearance().backgroundColor = UIColor.white
UISearchBar.appearance().tintColor = UIColor.white
UISearchBar.appearance().barTintColor = UIColor.white

然而只能得到这个结果。

enter image description here

虽然这种方式成功了,但间距看起来并不好。我宁愿把它变成白色。


你能提供一些额外的代码吗?例如,ContentView中的代码?这是因为通过添加searchable()修饰符,TextField变成了透明的。 - Visal Rajapakse
您可以实现init()函数来初始化这些属性。当我使用UINavigationBar.appearance()来改变tintColor时,它确实对我有用。但是,我仍在学习如何更改文本颜色。 - William Tong
5个回答

10

我通过使用这两个全局外观行来解决了这个问题。

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = .white
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = .black

enter image description here


2
对我来说,tintColor似乎没有效果。你尝试过将颜色设置为除黑色以外的任何颜色吗? - TalkingCode

2
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>])

2023年必须是被广泛接受的答案! - undefined

1

不是最理想的方法,但你可以尝试仅覆盖搜索栏的颜色方案/界面风格为暗色:

UISearchBar.appearance().overrideUserInterfaceStyle = .dark

这样,导航栏和应用程序的其余部分应该保持不受影响。


-1

通过更改应用了.searchable修饰符的视图的.preferredColorScheme(),可以将输入字段的文本颜色从黑色更改为白色。设置.preferredColorScheme(.dark)将把颜色设置为白色。


1
这也会改变通知栏(时间、电池、覆盖范围等)的颜色,因此我不认为这是一个有效的解决方案,因为目标是更改搜索栏的文本颜色。 - Jéluchu
我添加了一个答案,考虑到这一点,并且只更改搜索栏本身的颜色方案(界面样式):https://dev59.com/kcLra4cB1Zd3GeqPIGB3#75649611 - Martin

-1

.searchable之后设置.font.foregroundColor修饰符将会产生期望的结果,但截至本文撰写时(iOS 16),它仍无法与.background修饰符一起使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接