【问题标题】:Change colour of Picker within NavigationView在 NavigationView 中更改 Picker 的颜色
【发布时间】:2021-02-15 22:22:13
【问题描述】:

我正在尝试将此 NavigationView 嵌入到更大的视图中,但我似乎设置的任何内容都不会更改为此视图中 Picker 的背景颜色。

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

example image

可能有更好的设置来获得我想要的效果,但我不知道,我该如何更改 Picker 颜色?

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

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

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

    【讨论】:

    • 当我点击选择器时 - 选项 1-4 仍然是白色的 - 是否有不同的选项来设置它们?
    • 没有简单的方法
    • @AlexJ 为此更新了我的答案。如果需要,您可以获取 UITableView 并以相同的方式进行配置
    猜你喜欢
    • 2019-07-28
    • 2017-01-20
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    • 2015-08-24
    相关资源
    最近更新 更多