coco
coco

Reputation: 3136

SwiftUI two columns of text

I have a dynamic array of Strings, that I want to display in a 2-column format. This is my first stab at it:

    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)
            }
        }
    }

But very inelegant! What is a better way to do this?

Upvotes: 1

Views: 2724

Answers (1)

jnpdx
jnpdx

Reputation: 52407

LazyVGrid can be made to achieve your two-column layout:

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)
            }
        }
    }
}

Important note: Using .self for the id in a ForEach is not safe unless it is guaranteed that each word is unique and won't change locations in the grid (such as in my example where theWords is an immutable array). If either of those is not the case, make sure to give each word a unique ID

Upvotes: 3

Related Questions