Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView and SwiftUI?

How to create grid of square items (for example like in iOS Photo Library) with SwiftUI?

I tried this approach but it doesn't work:

var body: some View {     List(cellModels) { _ in         Color.orange.frame(width: 100, height: 100)     } } 

List still has UITableView style:

enter image description here

like image 781
Evgeny Mikhaylov Avatar asked Jun 05 '19 18:06

Evgeny Mikhaylov


People also ask

Does SwiftUI have CollectionView?

SwiftUI will not provide collection views or table views. Instead, you will use a List component to render lists of content. That said, you can of course wrap a UICollectionViewController in a SwiftUI View. So in this article, we are using List and Stacks to render the CollectionView.

What is a UICollectionView?

An object that manages an ordered collection of data items and presents them using customizable layouts.

Is SwiftUI ready for production?

SwiftUI is more than ready for simple applications, but at the time of this writing (iOS 15, beta 4), I don't think SwiftUI is production-ready yet for complex applications, mainly due to the issues with ScrollViews and the heavy reliance on UIViewRepresentable .


2 Answers

iOS 14 and XCode 12

SwiftUI for iOS 14 brings a new and nativ grid view that is easy to use, its called LazyVGrid: https://developer.apple.com/documentation/swiftui/lazyvgrid

You can start with defining an array of GridItem's. GridItems are used to specify layout properties for each column. In this case all GridItems are flexible.

LazyVGrid takes an array of GridItem's as its parameter and displays the containing views according to the defined GridItems.

import SwiftUI  struct ContentView: View {          let columns = [         GridItem(.flexible()),         GridItem(.flexible()),         GridItem(.flexible()),         GridItem(.flexible())     ]          var body: some View {         ScrollView {             LazyVGrid(columns: columns) {                 ForEach(0...100, id: \.self) { _ in                     Color.orange.frame(width: 100, height: 100)                 }             }         }     } } 

LazyVGrid in use

like image 160
KevinP Avatar answered Sep 17 '22 18:09

KevinP


One of the possible solutions is to wrap your UICollectionView into UIViewRepresentable. See Combining and Creating Views SwiftUI Tutorial, where they wrap the MKMapView as an example.

By now there isn’t an equivalent of UICollectionView in the SwiftUI and there’s no plan for it yet. See a discussion under that tweet.

To get more details check the Integrating SwiftUI WWDC video (~8:08).

Update:

Since iOS 14 (beta) we can use Lazy*Stack to at least achieve the performance of the collection view in the SwiftUI. When it comes to the layout of cells I think we still have to manage it manually on a per-row/per-column basis.

like image 38
Maciek Czarnik Avatar answered Sep 21 '22 18:09

Maciek Czarnik