SwiftUI 两列文本

SwiftUI two columns of text

我有一个动态字符串数组,我想以 2 列格式显示它。这是我第一次尝试:

    ForEach(0..<theWords.count, id: \.self) { ind in
        HStack {
            if ind.isMultiple(of: 2) {
                Text(theWords[ind])
                    .offset(x: -65, y: 0)
            }
            if !ind.isMultiple(of: 2) {
                Text(theWords[ind])
                    .offset(x: 65, y: -24)
            }
        }
    }

但是很不雅观!执行此操作的更好方法是什么?

LazyVGrid可以实现你的two-column布局:

struct ContentView: View {
    let theWords = ["Cat","Dog","Rat","Hamster","Iguana","Newt"]
    
    let columns: [GridItem] =
             Array(repeating: .init(.flexible()), count: 2)
    
    var body: some View {
        LazyVGrid(columns: columns) {
            ForEach(theWords, id: \.self) { word in
                Text(word)
            }
        }
    }
}

重要说明: .self 用于 ForEach 中的 id 不安全的 除非保证每个单词都是唯一的并且不会出现' t 更改网格中的位置(例如在我的示例中,theWords 是一个不可变数组)。如果其中任何一个不是这种情况,请确保为每个单词提供唯一的 ID