如何在 SwiftUI 中更改分段选取器的颜色外观? [英] How can I change Color appearance of Segmented Picker in SwiftUI?
问题描述
有谁知道如何实现这一目标?我有红色、绿色、黄色和蓝色四种颜色,我希望我选择的段具有指示颜色名称的背景/色调颜色.这是我的代码:
Does anyone know how to achieve this? I have four colors of red, green, yellow, and blue and I want my selected segment to have a background/tint color that is indicative of the color name. This is my code:
let objectColors = Color.allCases
@State private var selectedColorIndex = 0
//declared inside body view
Picker("Colors", selection: $selectedColorIndex) {
ForEach(0..<objectColors.count){ index in
Text(self.objectColors[index].rawValue).tag(index)
}
}
.pickerStyle(SegmentedPickerStyle())
.padding(10)
.onAppear {
UISegmentedControl.appearance().selectedSegmentTintColor = UIColor.generateUIColor(colorIndex: selectedColorIndex)
}
这是我要从中提取的列表
This is the list I'm pulling from
enum Color: String, CaseIterable {
case red, yellow, green, blue
}
我尝试过使用 onChange 或 onReceive(以及对子视图使用 Combine 的Just()")而不是 onAppear,但它们在操场上崩溃并且在 Xcode 上不起作用.我还在 UIAction 上看到了一个 WWDC 视频,我认为它非常适合更新视图更改,但我不知道如何翻译它.请问有人有什么建议或帮助吗?谢谢
I've tried using onChange or onReceive (and Combine's 'Just()' for subview) instead of onAppear but they crash on playgrounds and don't work on Xcode. I also saw a WWDC video on UIAction that I think will work great for updating view changes but I have no idea how to translate it. Does anyone one have any suggestions or help, please? Thanks
推荐答案
Here: 既然你使用的是 enum
那么选择的类型也应该是 enum
类型,你也您的自定义 enum
命名错误.
Here: Since you are using enum
then selected type should be enum
type as well, also you had wrong naming for your custom enum
.
struct ContentView: View {
@State private var selectedColor: ColorEnum = ColorEnum.blue
@State private var renderView: Bool = Bool()
var body: some View {
Group {
if renderView { SegmentedPickerView(selectedColor: $selectedColor) }
else { SegmentedPickerView(selectedColor: $selectedColor) }
}
.onChange(of: selectedColor) { _ in renderView.toggle() }
}
}
struct SegmentedPickerView: View {
@Binding var selectedColor: ColorEnum
init(selectedColor: Binding<ColorEnum>) {
self._selectedColor = selectedColor
UISegmentedControl.appearance().selectedSegmentTintColor = selectedColor.wrappedValue.ColorValue
}
var body: some View {
VStack {
Picker("", selection: $selectedColor) {
ForEach(ColorEnum.allCases, id: \.self) { item in
Text(item.rawValue)
}
}
.pickerStyle(SegmentedPickerStyle())
Text("You selected: " + selectedColor.rawValue)
.bold()
.shadow(radius: 10.0)
.padding()
}
.padding()
.background(Color.black.opacity(0.1).cornerRadius(10.0))
.foregroundColor(Color(selectedColor.ColorValue))
.padding()
}
}
enum ColorEnum: String, CaseIterable {
case red, yellow, green, blue
var ColorValue: UIColor {
get {
switch self {
case .red: return UIColor.red
case .yellow: return UIColor.yellow
case .green: return UIColor.green
case .blue: return UIColor.blue
}
}
}
}
这篇关于如何在 SwiftUI 中更改分段选取器的颜色外观?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!