【发布时间】:2019-11-16 20:33:31
【问题描述】:
我正在尝试遍历 SwuftUI 中的数组以在不同位置呈现多个文本字符串。手动遍历数组是可行的,但使用 forEach-loop 会产生错误。 在下面的代码示例中,我已经注释掉了手动方法(有效)。 这种方法在本教程中用于绘制线条 (https://developer.apple.com/tutorials/swiftui/drawing-paths-and-shapes)
(作为一个额外的问题:有没有办法通过这种方法获取各个位置的索引/键,而无需将该键添加到每行的位置数组中?)
我尝试了各种方法,例如 ForEach,在其中添加了identified(),并为闭包添加了各种类型定义,但我最终创建了其他错误
import SwiftUI
var positions: [CGPoint] = [
CGPoint(x: 100, y: 100),
CGPoint(x: 100, y: 200),
CGPoint(x: 100, y: 300),
]
struct ContentView : View {
var body: some View {
ZStack {
positions.forEach { (position) in
Text("Hello World")
.position(position)
}
/* The above approach produces error, this commented version works
Text("Hello World")
.position(positions[0])
Text("Hello World")
.position(positions[1])
Text("Hello World")
.position(positions[2]) */
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
【问题讨论】: