获取绑定的值

sas*_*ash 1 swift swiftui

我正在尝试@State根据传入的绑定在自定义初始值设定项中创建变量。我收到错误Cannot convert value of type 'Binding<Color>' to expected argument type 'Color'。有没有办法提取投标本身的原始价值?这是一个例子:

struct ContentView: View {
    
    @State var color = Color.red
    
    var body: some View {
        
        SomeView(color: $color)
    }
}

struct SomeView: View {
    
    @Binding var color: Color
    @State var someOtherColor: Color
    
    init(color: Binding<Color>) {
        
        _color = color
        
        _someOtherColor = State(initialValue: color) // ERROR: Cannot convert value of type 'Binding<Color>' to expected argument type 'Color'
    }
    
    var body: some View {
        Text("Hello, world!")
    }
}
Run Code Online (Sandbox Code Playgroud)

Dáv*_*tor 5

您可以使用 的wrappedValue属性Binding来访问其基础值。

_someOtherColor = State(initialValue: color.wrappedValue)
Run Code Online (Sandbox Code Playgroud)