当变量嵌套在对象中时,如何通过SwiftUI将绑定传递给子视图?

iOS*_*com 6 swift swiftui

这有效

import SwiftUI
struct ContentView : View {
    @State var val1: Int = 0
    var body: some View {
        MySubview(val1: $val1)
    }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView(val1: 0)
    }
}
#endif

struct MySubview : View {
    @Binding var val1: Int
    var body: some View {
        return Text("Value = \(val1)")
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当变量嵌套在对象中时,这将失败

import SwiftUI
struct MyStruct {
    let number: Int
}

struct ContentView : View {
    @State var val1 = MyStruct(number: 7)
    var body: some View {
        MySubview(val1: $val1.number)
    }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView(val1: 0)
    }
}
#endif

struct MySubview : View {
    @Binding var val1: Int
    var body: some View {
        return Text("Value = \(val1)")
    }
}
Run Code Online (Sandbox Code Playgroud)

显示错误: Generic parameter 'Subject' could not be inferred

如何传递嵌套变量作为对子视图的绑定?

kon*_*iki 9

该错误非常令人误解。数字必须是var,而不是let:

struct MyStruct {
    var number: Int
}
Run Code Online (Sandbox Code Playgroud)

更改它,它将正常工作。

  • 使用SwiftUI,您不能相信任何错误!甚至没有它的位置。有时,代码顶部的错误是由于底部(或另一个文件)中的某些错误导致的。这很烦人,我希望他们能随着时间的推移改善它。 (2认同)

Ada*_*hus 7

除了var number: Intkontiki 指出的需要之外,您的代码很好。

为了帮助理解在视图之间传递绑定,我准备了以下代码,它@Binding以稍微不同的方式显示了使用:

import SwiftUI

struct Zoo    { var shed:    Shed     }
struct Shed   { var animals: [Animal] }
struct Animal { var legs:    Int      }

struct ZooView : View {
  @State var zoo = Zoo( shed: Shed(animals:
      [ Animal(legs: 2), Animal(legs: 4) ] ) )

  var body: some View {
    VStack {
      Text("Legs in the zoo directly:")
      Text("Animal 1 Legs: \(zoo.shed.animals[0].legs)")
      Text("Animal 2 Legs: \(zoo.shed.animals[1].legs)")
      Divider()
      Text("And now with nested views:")
      ShedView(shed: $zoo.shed)
    }
  }
}

struct ShedView : View {
  @Binding var shed: Shed

  var body: some View {
    ForEach(shed.animals.indices) { index in
      VStack {
        Text("Animal: \(index+1)")
        AnimalView(animal: self.$shed.animals[index])
      }
    }
  }
}

struct AnimalView : View {
  @Binding var animal: Animal

  var body: some View {
    VStack {
      Text("Legs = \(animal.legs)")
      Button(
      action: { self.animal.legs += 1 }) {
        Text("Another leg")
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

特别ShedView是给了一个棚子的绑定,它在棚子里的动物数组中查找一个动物,并将绑定给动物传递给AnimalView