ios - 如何在SwiftUI分段选择器中更改选定的分段颜色

标签 ios swift swiftui

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

我尝试将两种修饰符用于选择器 View ,还尝试从外观代理中修改色调颜色。不幸的是,它们似乎都不起作用。


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?

最佳答案

从beta 3开始,可以使用selectedSegmentTintColor更改所选段的颜色。

要更改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)
}

Segmented Controll

关于ios - 如何在SwiftUI分段选择器中更改选定的分段颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57735761/

相关文章:

ios - 如何在 SwiftUI 中以横向模式预览设备?

ios - Settings.bundle,输入验证

swift - 重写绑定(bind)方法 (Swift) - 错误 : Value of type 'Any' has no member 'addObserver'

swift - 如何在 Swift 中渲染本地化日期间隔

ios - SKEmitterNode 粒子在开始时滞后

ios - 如何在 SwiftUI 中显示键盘时显示完整列表

swiftui - 如何在不在编辑模式下的 SwiftUI 列表中重新排序行?

ios - 如何将任何基数转换为基数 10?

iOS Facebook 分享

ios - Swift:如何以枚举为键对 HashMap 进行编码?