这有效
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
如何将嵌套变量作为绑定(bind)传递给 subview ?
最佳答案
该错误非常具有误导性。 Number 必须是 var,而不是 let:
struct MyStruct {
var number: Int
}
改变它,它会正常工作。
关于swift - 当变量嵌套在对象中时,如何使用 SwiftUI 将绑定(bind)传递给 subview ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56733363/