如何将 UISegmentedControl 和 SwiftUI 形状设置为相同的颜色?

How to set a UISegmentedControl and SwiftUI shape to the same color?

我创建了一个 RoundedRectangle 并将其 foregroundColor 设置为蓝色

RoundedRectangle(cornerRadius: 10).foregroundColor(.blue)

我创建了一个自定义的 SegmentedControl 结构并将其颜色设置为蓝色

UISegmentedControl.appearance().selectedSegmentTintColor = .blue

但是,对象呈现为 totally different shades of blue。如何将它们设置为相同的蓝色?

完整代码:

import SwiftUI

struct ContentView: View {
  @State var choice = Choice.a

  var body: some View {
    VStack {
      Menu { } label: {
        Text("Menu")
          .foregroundColor(.white)
          .padding(5)
          .background(
            RoundedRectangle(cornerRadius: 10)
              .foregroundColor(.blue)
          )
      }
      SegmentedControl(choice: $choice)
        .padding(.horizontal, 50)
    }
  }
}

struct SegmentedControl: View {
  @Binding var choice: Choice
  var choices = [Choice.a, Choice.b]
  
  init(choice: Binding<Choice>) {
    UISegmentedControl.appearance().selectedSegmentTintColor = .blue
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .normal)
    self._choice = choice
  }
  
  var body: some View {
    Picker("Which tab?",
           selection: $choice,
           content: {
      ForEach(choices, id: \.self) {
        Text([=10=].description())
      }
    })
      .pickerStyle(.segmented)
  }
}

enum Choice {
  case a
  case b
  
  func description() -> String {
    var str = ""
    switch self {
    case .a:
      str = "Choice A"
    case .b:
      str = "Choice B"
    }
    return str
  }
}

您好,您可以在资产中创建一个 'Color Set',然后这样调用您的颜色:

RoundedRectangle(cornerRadius: 10).foregroundColor(Color("the name of your Color"))

UISegmentedControl.appearance().selectedSegmentTintColor = Color("the same Color")

区别在于Color.blue使用UIColor.systemBlue

所以你可以用两种方法来处理它

首先,你可以改变矩形

RoundedRectangle(cornerRadius: 10)
    .foregroundColor(Color(UIColor.blue))

或者二次换控件

UISegmentedControl.appearance().selectedSegmentTintColor = .systemBlue

这些更改中的任何一个都会与另一个相匹配。看你喜欢哪个。