如何在两个SwiftUI视图之间传递String数组作为绑定?

时间:2020-10-11 13:37:54

标签: swift swiftui

我有两个SwiftUI视图,ContentViewSecondView。我想与String共享一个ContentView中的SecondView数组。 SecondView仅需要使用VStack显示内容。

我正在尝试使用@StateBinding属性来实现此目标,如下所示。请注意,我需要学习如何手动遍历String数组中的每个项目,而不是使用类似List的东西。

我的当前代码

struct ContentView: View {
    @State var items: [String] = ["a", "b", "c"]
    var body: some View {
        SecondView<String>(elements: $items)
    }
} 

struct SecondView: View {
    var elements: Binding<[String]>
    
    var body: some View {
        VStack {
            // Compiler errors happen in the next line.
            ForEach(elements, id: \.self) { (v: String) in
                Text(v)
            }
        }
    }
}

尝试编译以上代码会在ForEachSecondView附近产生以下错误。

1. Cannot convert value of type '(String) -> Text' to expected argument type '(Binding<[String]>.Element) -> Text'
2. Generic struct 'ForEach' requires that 'Binding<[String]>' conform to 'RandomAccessCollection'

我非常感谢任何人关于如何实现此目标的想法或答案。我对SwiftUI非常陌生,无法理解这个概念。

-更新-

感谢@Asperi的快速响应。对于以后发现此问题的任何人,Binding<String>都有一个位置,只是不作为变量的类型。

当您需要Binding<String>的自定义初始化程序时,必须使用

struct

struct SecondView: View {
    @Binding var elements: [String]

    init(_ elements: Binding<[String]>){
        self._elements = elements
    }

    // Hidden implementation details
}

1 个答案:

答案 0 :(得分:1)

这里是正确的代码

struct ContentView: View {
    @State var items: [String] = ["a", "b", "c"]
    var body: some View {
        SecondView(elements: $items)
    }
}

struct SecondView: View {
    @Binding var elements: [String]
    
    var body: some View {
        VStack {
            ForEach(elements, id: \.self) { v in
                Text(v)
            }
        }
    }
}