改变NavigationView中选择器的颜色



我试图将这个NavigationView嵌入到一个更大的视图中,但是我似乎没有设置任何东西会改变这个视图中选择器的背景颜色。

当我执行以下操作时,除了选择器本身之外的所有内容都被设置为黑色,但选择器仍然是白色,就像这样…

示例图片

可能有一个更好的设置来获得我想要的效果,但不知道,我如何改变选择器的颜色?

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

最新更新