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

swi*_*fty 6 swift swiftui

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

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


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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 8

最近我遇到了类似的问题,我需要自定义backgroundforeground颜色,因为SwiftUI SegmentedControl我发现这篇文章也很有帮助,但我也想分享我发现的并且我现在正在使用的其他解决方案。有一个非常好的包,称为SwiftUI Introspect,它允许......

内省底层 UIKit 组件SwiftUI

使用这个包我创建了以下内容SegmentedControl 在此输入图像描述 有了这个代码:

VStack {
    Picker("Activity view", selection: $selectedActivity) {
        ForEach(ActivityView.allCases) { activity in
            Text(activity.description)
        }
    }
    .introspectSegmentedControl { segmentedControl in
        segmentedControl.backgroundColor = .clear
        segmentedControl.tintColor = TCHColors.SegmentedControl.backgroundSelected
        segmentedControl.selectedSegmentTintColor = TCHColors.SegmentedControl.backgroundSelected
        segmentedControl.setTitleTextAttributes([
            NSAttributedString.Key.foregroundColor: TCHColors.SegmentedControl.selectedText
        ], for: .selected)
        segmentedControl.setTitleTextAttributes([
            NSAttributedString.Key.foregroundColor: TCHColors.SegmentedControl.normalText
        ], for: .normal)
    }
    .pickerStyle(.segmented)
}
.padding(.horizontal, 16)
Run Code Online (Sandbox Code Playgroud)

您可以使用此包从 SwiftUI 访问许多其他底层组件。


Moj*_*ini 7

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

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

So it will be like:

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

分段控制

  • 非常感谢!正是我要找的东西!!! (2认同)
  • 请注意,这些属性没有代码完成功能,但如果您键入它们,它们就会编译 (2认同)
  • 只需将其设置为“UIColor(Color.accentColor)”@StuFFmc (2认同)