【问题标题】:How to use Binding<Color> in SwiftUI?如何在 SwiftUI 中使用 Binding<Color>?
【发布时间】:2021-12-30 13:54:07
【问题描述】:

如何在 SwiftUI 中动态更改颜色,如本例所示

@Binding var randomColor: Color

public var body: some View {
    ZStack {
        Circle()
            .stroke(lineWidth: 20)
            .opacity(0.5)
            .foregroundColor($randomColor)
    }
}

这不起作用,因为.foregroundColor 只需要Color。有什么方法可以将@Binding 与颜色一起使用,或者这不是在 SwiftUI 中使用的方法吗?

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    您只需要在需要更改和读取变量值的子视图中使用 $variableName 形式的绑定变量。

    如果您的所有子视图正在读取当前设置的值,您将直接访问 variableName。因此,您提供的示例中的身体将是

    public var body: some View {
        ZStack {
            Circle()
                .stroke(lineWidth: 20)
                .opacity(0.5)
                .foregroundColor(randomColor)
        }
    }
    

    此外,使用@Binding 表示您的视图将需要编辑父视图拥有的状态变量的值。如果您不对其进行任何更改,则根本没有必要将其声明为绑定。

    另一方面,如果您更改变量的值,但此视图“拥有”该变量,您将改用@State

    例如:

    struct ContentView: View {
      // owned by this view (and with a starting value defined)
      @State var myColor: Color = .accessColor
    
      var body: some View {
        VStack {
          // This subview is allowed to change the value, so it takes a binding
          ColorPicker("Color", selection: $myColor)
    
          // This subview is only going to display the color, so it takes a read-only property
          ExampleColorView(color: myColor)
        }
      }
    }
    
    struct ExampleColorView: View {
      var color: Color
    
      var body: some View {
        ZStack {
          Circle()
            .stroke(lineWidth: 20)
            .opacity(0.5)
            .foregroundColor(color)
        }
      }
    }
    

    每当父视图的 myColor 变量发生变化时,SwiftUI 系统就会创建一个新的 ExampleColorView 结构并定义新的颜色——它会发现旧视图和新视图之间的差异,并重绘屏幕。

    【讨论】:

    • 该值将更改为 yes。所以唯一的事情就是把它改成@State
    猜你喜欢
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 2021-07-14
    • 1970-01-01
    • 2019-10-22
    • 2019-12-11
    • 2021-03-31
    相关资源
    最近更新 更多