如何在SwiftUI分段选择器中更改选定的分段颜色 [英] How to change selected segment color in SwiftUI Segmented Picker

查看:284
本文介绍了如何在SwiftUI分段选择器中更改选定的分段颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to set the selected segment color in a SwiftUI segmented picker and change the text color to white.

我已经尝试过同时使用选择器视图的修饰符和修改外观代理的色调颜色.不幸的是,它们似乎都不起作用.

I have tried both using the modifiers for the picker view and modifying the tint color from the appearance proxy. None of them seem to work, unfortunately.


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?

Is there any way to do this in SwiftUI, or should I just use the UISegmentedControl by using UIViewControllerRepresentable?

推荐答案

selectedSegmentTintColor自beta 3开始可用,用于更改所选段的颜色.

selectedSegmentTintColor is available since beta 3 for changing the color of the selected segment.

要更改textColor,应将setTitleTextAttributes用于.selected状态和.normal状态(未选中).

For changing the textColor, you should use setTitleTextAttributes for .selected state and .normal state (unselected).

因此它将是:

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

这篇关于如何在SwiftUI分段选择器中更改选定的分段颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆