NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: LazyVGrid and Array

Forums > SwiftUI

    let datas = ["a","a","a1","b","b43","b", "f", "g"]

    let columns = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible()),
    ]

    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns, spacing: 20) {
                ForEach(datas, id: \.self) { item in
                    Text(item)
                }
            }
            .padding(.horizontal)
        }
        .frame(maxHeight: 300)
  }

Dear community, this Code is the third example from the article "How to position views in a grid using LazyVGrid and LazyHGrid" from Hacking with swift. I change the array and make all GridItems flexible. All similar elements of the array datas are not shown. Here, the second a and the second b are not shown. The part of the table is shown, but it is empty. Why are elements are not shown? Thank you!

   

try this , .self wants ForEach elements unique, which is not the case in your array, so we use this way of accesing indices and calling

 ScrollView {
                   LazyVGrid(columns: columns, spacing: 20) {
                       ForEach(datas.indices) { index in
                           let item = datas[index]
                           Text(item)
                       }
                   }
                   .padding(.horizontal)
               }
               .frame(maxHeight: 300)
    }

1      

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.