Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UI - How to make Image Grids?

Tags:

swift

swiftui

Need to create a grid of images with SwiftUI, that dynamically change rows according to screen width.

When I use List, I can only get one column..

I tried Hstacks to make 2 columns, but then it doesn't work dynamically for screen width.

Ex: iPhone portrait should have 1 column Ex: iPhone landscape should have 2 column

import SwiftUI

struct ProductGrid : View {
    var body: some View {

        List(0 ..< 5) { item in

            VStack() {
                Image("product")
                HStack {

                   ProfileImageSmall()
                        VStack {
                            Text("Product")

                            Text("Username")


                        }


                    }



            }

        }
    }
}

How can I make a grid that column count adapts to screen width?

like image 754
Mane Manero Avatar asked Jun 14 '19 18:06

Mane Manero


1 Answers

Available for XCode 12

import SwiftUI

//MARK: - Adaptive
struct ContentView: View {
    
    var body: some View {
        ScrollView {
            LazyVGrid(columns: [GridItem(.adaptive(minimum:100))]) {
                ForEach(yourObjects) { object in
                    YourObjectView(item: object)
                }
            }
        }
    }
}

//MARK: - Custom Columns
struct ContentView: View {
        
    var body: some View {
         ScrollView {   
             LazyVGrid(columns: Array(repeating: GridItem(), count: 4)) {
                 ForEach(yourObjects) { object in
                     YourObjectView(item: object)
                 }
             }
         }
    }
}

Don't forget replace the info objects with your info and YourObjectView with your customView.

like image 115
gandhi Mena Avatar answered Oct 04 '22 16:10

gandhi Mena