目标:简单地通过NavigationLink将每个List行的结构传递给辅助视图。
小步骤(之前的目标):仅仅将一个字符串数组的成员传递给辅助视图。
问题:辅助视图在参数调用中需要BindingString值,而在上下文中需要闭包String值。
因此,我必须在调用之前将@State变量设置为当前/上下文值。
这是我的问题。我不能简单地将绑定变量等同于当前上下文变量;因为在 SwiftUI 中,此类语句仅限于基于 View 的内容。
这不起作用:
下面是实际的代码:
import SwiftUI
struct ContentView: View {
@State var name = "" //... load with inital value to avoid having to add a call parameter.
var body: some View {
let myArray = ["Larry", "Moe", "Curly"]
NavigationView {
List(myArray, id: \.self) { theStooge in
NavigationLink(destination: SecondView(stoogeName: theStooge)) {
Text(theStooge)
}
}
.navigationBarTitle("Three Stooges").navigationBarTitleDisplayMode(.inline)
}
}
}
struct SecondView: View {
@Binding var stoogeName: String
var body: some View {
Text("Hello \(name)")
}
}
我只能通过NavigationLink的目标参数中的文本(“Hello World”)创建秒视图。但这不是很有帮助。我想将数据(数据结构)传递给每个List成员的辅助View。
但是我需要设置一个绑定变量。怎么做?
我必须陪审团操纵环境对象或单例吗?
绑定可以设置为动态属性,但您的数组是常量局部变量。以下是使用绑定的可能解决方案:
struct ContentView: View {
@State var name = "" //... load with inital value to avoid having to add a call parameter.
@State private var myArray = ["Larry", "Moe", "Curly"]
var body: some View {
NavigationView {
List(myArray.indices, id: \.self) { index in
NavigationLink(destination: SecondView(stoogeName: $myArray[index])) {
Text(myArray[index])
}
}
.navigationBarTitle("Three Stooges").navigationBarTitleDisplayMode(.inline)
}
}
}