首页 > 解决方案 > SwiftUI - 如何更改嵌套在表单中的选取器的复选标记颜色

问题描述

我正在尝试更改 SwiftUI 中复选标记的颜色,该复选标记用于嵌套在表单内的选取器中。我试过了:

UINavigationBar.appearance().tintColor = .black

但这只会改变“< Back”的颜色。

struct ContentView: View {

    @State private var selectedMode = 0
    private var modes = ["#1", "#2"]


    var body: some View {
        NavigationView {
            Form {
                Section(header:Text("").font(.title)
                    .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
                ){
                    Picker(selection: $selectedMode, label: Text("Modes")) {
                        ForEach(0 ..< modes.count, id: \.self) {
                            Text(self.modes[$0])
                                .foregroundColor(Color.red)
                        }
                    }
                }
            }
        }
    }
}

在此处输入图像描述

标签: swiftswiftuiuinavigationbar

解决方案


在这里(使用 Xcode 11.4 测试)

演示

var body: some View {
    NavigationView {
        Form {
            Section(header:Text("").font(.title)
                .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
            ){
                Picker(selection: $selectedMode, label: Text("Modes")) {
                    ForEach(0 ..< modes.count, id: \.self) {
                        Text(self.modes[$0])
                            .foregroundColor(Color.red)
                    }
                }
            }
        }
    }.accentColor(Color.black)   // << fix !!
}

注意: .accentColor适用于所有NavigationView控件,因此UINavigationBar.appearance().tintColor = .black不需要。


推荐阅读