In this tutorial, we will learn about CollectionView and how can we create CollectionView using List & ScrollView in SwiftUI.
SwiftUI is an innovative, exceptionally simple way to build user interfaces across all Apple platforms with the power of Swift. Build user interfaces for any Apple device using just one set of tools and APIs. With a declarative Swift syntax that’s easy to read and natural to write, it works seamlessly with new Xcode design tools to keep your code and design perfectly in sync. Automatic support for Dynamic Type, Dark Mode, localization, and accessibility means your first line of SwiftUI code is already the most powerful UI code you’ve ever written.
let’s create the Collection view using List and display random colours collection.
Getting Started
SwiftUI version: 2
iOS version: 14
Xcode: 12
Using List:
First Create a SwiftUI project.
1 2 3 4 5 6 7 8 9 10 11 12 |
List() { ForEach(0..<8) { i in HStack { ForEach(0..<3) { j in ZStack(alignment: .center) { } .frame(width:size, height:size) .background(Color.random) } } } } |
1 |
var size = UIScreen.main.bounds.width/3-16 |
Here, I have use 2 ForEach loop to create Collection View and I have write a extension of Color.
1 2 3 4 5 6 7 8 9 |
extension Color { static var random: Color { return Color( red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1) ) } } |
Thats enough code to create a CollectionView Using List.
Screenshot
Using ScrollView:
We can also create collectionview layout using ScrollView. Just Replace ScrollView with ScrollView
1 2 3 4 5 6 7 8 9 10 11 12 |
ScrollView{ ForEach(0..<8) { i in HStack { ForEach(0..<3) { j in ZStack(alignment: .center) { } .frame(width:size, height:size) .background(Color.random) } } } } |
I hope this code will help you better to understand about CollectionView. If you feel any doubt or query please comment below.
Thank you.