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

时间:2019-06-24 09:14:39

标签: 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)")
    }
}

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

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)")
    }
}

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

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

2 个答案:

答案 0 :(得分:5)

该错误非常容易引起误解。数字必须是var,而不是let:

struct MyStruct {
    var number: Int
}

更改它,它将正常工作。

答案 1 :(得分:0)

您的代码很好,除了需要像kontiki指出的那样:“ Int”。

为了帮助理解在视图之间传递绑定,我准备了以下代码,该代码以略有不同的方式显示了@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")
      }
    }
  }
}

特别是,ShedView被赋予了与棚子的绑定,并在棚子中的一系列动物中查找了一个动物,并将与该动物的绑定传递给AnimalView。