SwiftUI选择器有修改标签颜色的修饰符吗?

9

我想把SwiftUI Picker标签的颜色从蓝色改为黑色,尝试了.foregroundColor(.black).tint(.black),但颜色仍然是蓝色。

@State var privacy = Privacy.open
enum Privacy: String, CaseIterable, Identifiable {
    case open = "Open"
    case closed = "Closed"
    var id: String {
        self.rawValue
    }
}
    
var body: some View {
    Picker("privacy", selection: $privacy) {
        ForEach(Privacy.allCases) { value in
            Text(value.rawValue)
                .tag(value)
        }
    }
    .pickerStyle(.menu)
    .tint(.black)
    .foregroundColor(.black)
}

3个回答

23

我尝试了foregroundStyleaccentColor,但只有accentColor起作用。它确实有一个未来废弃的警告,但你现在应该能够使用它。

.accentColor(.orange)

1
这对我有用,但只有当我明确定义'.pickerStyle(.menu)'时。 - SPM

6

正如其他用户所提到的,.accentColor(.orange) 可以使用,但会有警告。

使用 .tint(.orange) 不会有此警告,并且可以为选择器文本添加颜色。


1

对我来说,既不是tint也不是accentColor有效。我创建了一个视图修饰符,在其中更新了setTitleTextAttributes.foregroundColor值。

struct SegmentPickerModifier: ViewModifier {

init() {
    let colorAppearance = UISegmentedControl.appearance()
    colorAppearance.backgroundColor = .red
    colorAppearance.selectedSegmentTintColor = .blue
    colorAppearance.tintColor = .green
    colorAppearance.setTitleTextAttributes([.foregroundColor : UIColor.white], for: .normal)
    colorAppearance.setDividerImage(
        UIImage(),
        forLeftSegmentState: .normal,
        rightSegmentState: .normal,
        barMetrics: .default
    )

}

func body(content: Content) -> some View {
    content
}
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接