自定义“可搜索”搜索字段 SwiftUI iOS 15

问题描述 投票:0回答:5

在 iOS 15 上的 SwiftUI 中使用新的

.searchable()
修饰符时,我无法自定义搜索栏外观。具体来说,我不希望它与我用于导航栏的颜色看起来很好。

我尝试像这样改变

.appearance()

UISearchBar.appearance().backgroundColor = UIColor.white
UISearchBar.appearance().tintColor = UIColor.white
UISearchBar.appearance().barTintColor = UIColor.white

但只得到了这个。

尽管这种方法很成功,但间距看起来不太好。我宁愿把它染成白色。

swift search swiftui uisearchbar
5个回答
9
投票

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

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


0
投票

.font
之后设置
.foregroundColor
.searchable
修饰符将获得所需的结果,但在撰写本文时仍然无法与
.background
修饰符一起使用(iOS 16)。


0
投票

不理想,但您可以尝试仅将搜索栏的配色方案/界面样式覆盖为深色:

UISearchBar.appearance().overrideUserInterfaceStyle = .dark

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


0
投票

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

-1
投票

通过更改应用了

.preferredColorScheme()
修改器的视图的
.searchable
,可以将输入字段的文本颜色从黑色更改为白色。设置
.preferredColorScheme(.dark)
会将颜色设置为白色。

© www.soinside.com 2019 - 2024. All rights reserved.