ios - 在 NavigationView 中更改 Picker 的颜色
问题描述
我正在尝试将此 NavigationView 嵌入到更大的视图中,但我似乎设置的任何内容都不会更改为此视图中 Picker 的背景颜色。
当我执行以下操作时,除了 Picker 本身之外的所有内容都设置为黑色,但选择器保持白色,就像这样......
可能有更好的设置来获得我想要的效果,但不知道,我该如何更改 Picker Color?
struct ContentView: View {
@State var value = ""
init(){
UITableView.appearance().backgroundColor = .clear
UINavigationBar.appearance().backgroundColor = .clear
}
var body: some View {
NavigationView {
ZStack {
Color.black
.ignoresSafeArea()
Form {
Picker(selection: $value, label: Text("This")) {
Text("1").tag("1")
Text("2").tag("2")
Text("3").tag("3")
Text("4").tag("4")
}
}
}
}
}
}
解决方案
为此使用listRowBackground
。
Picker(selection: $value, label: Text("this")) {
...
}.listRowBackground(Color.green)
为了改变打开的选择器中单元格的背景颜色,你必须通过 UIKit 设置它们。
extension View {
func cellBackgroundColor(_ uiColor: UIColor) -> some View {
background(TableCellGrabber { cell in
cell.backgroundView = UIView()
cell.backgroundColor = uiColor
})
}
}
struct TableCellGrabber: UIViewRepresentable {
let configure: (UITableViewCell) -> Void
func makeUIView(context: Context) -> UIView {
UIView()
}
func updateUIView(_ uiView: UIView, context: Context) {
DispatchQueue.main.async {
if let cell: UITableViewCell = uiView.parentView() {
configure(cell)
}
}
}
}
extension UIView {
func parentView<T: UIView>() -> T? {
if let v = self as? T {
return v
}
return superview?.parentView()
}
}
用法:
Picker(selection: $value, label: Text("this")) {
Text("1").tag("1").cellBackgroundColor(.red)
Text("2").tag("2").cellBackgroundColor(.red)
Text("3").tag("3").cellBackgroundColor(.red)
Text("4").tag("4").cellBackgroundColor(.red)
}
或者您可以使用特殊Group
视图将其应用于所有分组项目。
Picker(selection: $value, label: Text("this")) {
Group {
Text("1").tag("1")
Text("2").tag("2")
Text("3").tag("3")
Text("4").tag("4")
}.cellBackgroundColor(.red)
}
推荐阅读
- gulp - 运行一个需要当前文件路径和名称的 gulp 插件
- python - 从 python 或 SQL 中的 url 字段中提取字符串
- java - 如何在 Spring Boot 中运行自动装配线程
- jsp - 如何访问我在脚本中的 c:set 中设置的值?
- python - Pyqt5中KeyEvent的正确处理,捕捉KeyPressEvent的问题
- webgl - WebGL 多个独立对象
- python - 有没有办法减少在数据框中循环的条件
- python - 用于 ActiveX 对象的 PyQt5 包装器,而不是 WX 包装器
- javascript - 无法创建 2d 物理游戏引擎 (JavaScript)
- java - 使用语音命令搜索