我正在使用
.searchable()
的外观 API 自定义 SwiftUI 的 UISearchBar
修饰符的外观。
除了文本字段的字体之外,几乎所有内容都有效,我不知道为什么(设置取消按钮的字体有效,或者设置文本字段的背景颜色或文本颜色也有效,所以正确的参考就在那里).
空谈很便宜,给我看代码!
let textAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.systemBlue, // this works
.font: UIFont.boldSystemFont(ofSize: 15) // this doesnt
]
let placeholder = NSAttributedString(
string: "Search...", // this doesnt
attributes: [
.foregroundColor: UIColor.systemGray, // this works
.font: UIFont.boldSystemFont(ofSize: 15) // this doesnt
])
let textFieldAppearance = UITextField
.appearance(whenContainedInInstancesOf: [UISearchBar.self])
textFieldAppearance.backgroundColor = .red // this works
textFieldAppearance.defaultTextAttributes = textAttributes // color works, font not
textFieldAppearance.attributedPlaceholder = placeholder // color works, font or text not
我想是时候提交“雷达”反馈了?
我有做
UISearchTextField.appearance()
let appearance = UISearchTextField.appearance()
appearance.backgroundColor = .white.withAlphaComponent(0.15)
appearance.tintColor = .white
// Text attributes
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.white,
.font: UIFont.boldSystemFont(ofSize: 15),
]
appearance.defaultTextAttributes = attributes
// Placeholder attributes
let attributePlaceHolder: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.white.withAlphaComponent(0.5),
.font: UIFont.boldSystemFont(ofSize: 15),
]
appearance.attributedPlaceholder = NSAttributedString(string: "Search", attributes: attributePlaceHolder)
除此之外我们还需要在.searchable之后设置字体
.searchable(text: $viewModel.searchText,
placement: .navigationBarDrawer(displayMode: .always),
prompt: "Search")
.font(.system(size: 14)) // This is also required
因为当搜索栏未激活时,它工作正常,但是当 SearchBarController 激活时,字体会发生变化。
我还没有找到可靠的自定义方法,下面发布的解决方案中,当 SwiftUI 重新渲染视图(滚动或仅在搜索栏上键入)时,搜索栏上会出现故障,这在真实设备(模拟器上没有那么多)。
旧答案:
远非理想,我找到了一种让它发挥作用的方法,即内省视图,搜索
UITextField
并直接设置字体。最简单的方法是使用像 SwiftUI-Introspect (https://github.com/siteline/SwiftUI-Introspect) 这样的库。
然后在
View
上,您正在使用 .searchable()
:
.introspectTextField { textField in
textField.font = UIFont.boldSystemFont(ofSize: 15)
}
已修复!完美的解决方案是使用外观 API,但我想我们必须等到 iOS 16...
在
.font
之后设置 .foregroundColor
和 .searchable
修饰符将获得所需的结果,但在撰写本文时(iOS 16),它仍然无法与 .background
修饰符(如果您想要的话)一起使用。