【问题标题】:How to change selected segment color in SwiftUI Segmented Picker如何在 SwiftUI Segmented Picker 中更改选定的段颜色
【发布时间】:2020-01-04 05:46:29
【问题描述】:

我想在 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)
    }
}

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

【问题讨论】:

  • 如果我们想在同一个视图中为另一个分段选择器设置不同的色调颜色应该怎么做?

标签: ios swift swiftui


【解决方案1】:

原生(但有限

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)

【讨论】:

  • 请注意,这些属性没有代码完成,但如果您键入它们,它们将编译
  • 您可以使用 UISegmentedControl.appearance().backgroundColor = .blue 更改未选中段的颜色
  • 嘿@mojtaba-hosseini @mike 知道如何让它成为AccentColor
  • 只要设置成UIColor(Color.accentColor)@StuFFmc
  • 哦,谢谢@MojtabaHosseini 我实际上在做UIColor(named: "AccentColor")!。我不知道有那个方便的转换器:)
【解决方案2】:

这个回答对我有帮助,但我想补充一点。我使用的颜色是视图的参数,因此将这些方法放在 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
        }
    }
}

【讨论】:

    【解决方案3】:

    这是我在 SwiftUI 中工作的解决方案:

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

    【讨论】:

      猜你喜欢
      • 2023-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 2020-01-14
      • 2019-07-28
      • 1970-01-01
      相关资源
      最近更新 更多