如何在 SwiftUI Segmented Picker 中更改选定的段颜色

How to change selected segment color in SwiftUI Segmented Picker

我想在 SwiftUI 分段选择器中设置选定的分段颜色并将文本颜色更改为白色。

我已经尝试过使用选择器视图的修改器和修改外观代理的色调。不幸的是,None 其中似乎有效。


import SwiftUI

struct PickerView: View {

    @State var pickerSelection = 0

    init() {
        UISegmentedControl.appearance().tintColor = UIColor.blue
    }

    var body: some View {
        Picker(selection: $pickerSelection, label: Text("")) {
            Text("Active").tag(0).foregroundColor(Color.white)
            Text("Completed").tag(1)
        }.pickerStyle(SegmentedPickerStyle()).foregroundColor(Color.orange)
    }
}

在 SwiftUI 中有什么方法可以做到这一点,还是我应该通过使用 UIViewControllerRepresentable 来使用 UISegmentedControl?

原生(但受限

SwiftUI 当前不支持本机 SegmentedPicker 样式(请参阅答案底部的解决方法)。但是使用 .colorMultiply() 修饰符将颜色应用于分段选择器的方法有限:


完全控制使用 UIAppearance

selectedSegmentTintColor 自 beta 3 起可用于更改所选段的颜色。

要更改 textColor,您应该使用 setTitleTextAttributes 用于 .selected 状态和 .normal 状态(未选择)。

所以它会像:

init() {
    UISegmentedControl.appearance().selectedSegmentTintColor = .blue
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.blue], for: .normal)
}

另外,正如 mike 提到的,您也可以像这样设置背景颜色:

UISegmentedControl.appearance().backgroundColor = .yellow

此外,别忘了您也可以设置 SwiftUI 颜色!例如:

UISegmentedControl.appearance().selectedSegmentTintColor = UIColor(Color.accentColor)

这是我在 SwiftUI 中运行的解决方案:

init(){

    UISegmentedControl.appearance().selectedSegmentTintColor = .green
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.black], for: .selected)

    }

这个回答对我有帮助,但我想补充一点。我使用的颜色是视图的参数,因此将这些方法放在 init 中不允许我访问颜色。

或者,您可以直接在分段选择器上使用 onAppear 方法,就像这样。

import SwiftUI

struct PickerView: View {
    var color: UIColor   
    @State var pickerSelection = 0

    var body: some View {
        Picker(selection: $pickerSelection, label: Text("")) {
            Text("Active").tag(0).foregroundColor(Color.white)
            Text("Completed").tag(1)
        }.pickerStyle(SegmentedPickerStyle()).foregroundColor(Color.orange)
        .onAppear {
            UISegmentedControl.appearance().tintColor = color
        }
    }
}