首页 > 解决方案 > 在 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")
                    }
                }
            }
        }
    }
}

标签: iosswiftswiftui

解决方案


为此使用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)
}

推荐阅读