How to create grid in SwiftUI

2020-02-15 02:22发布

问题:

I know that we can create a List in vertical SwiftUI like this,

struct ContentView : View {
    var body: some View {
        NavigationView {
            List {
                Text("Hello")
            }
        }
    }
}

but is there any way that we could split the list in 2 or 3 or maybe more spans that covers the screen like a grid like we did in UICollectionView

回答1:

You can create your customView like this to achieve UICollectionView behavior:-

struct ContentView : View {
    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            ScrollView(showsHorizontalIndicator: true) {
                HStack {
                    ForEach(0...10) {_ in
                        GridView()
                    }
                }
            }
            List {
                ForEach(0...5) {_ in
                    ListView()
                }
            }
            Spacer()
        }
    }
}

struct ListView : View {
    var body: some View {
        Text(/*@START_MENU_TOKEN@*/"Hello World!"/*@END_MENU_TOKEN@*/)
        .color(.red)
    }
}

struct GridView : View {
    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            Image("marker")
                .renderingMode(.original)
                .cornerRadius(5)
                .frame(height: 200)
                .border(Color.red)
            Text("test")
        }
    }
}



回答2:

Checkout ZStack based example here

Grid(0...100) { _ in
    Rectangle()
        .foregroundColor(.blue)
}



标签: swift swiftui