Porting UICollectionView To SwiftUI
Add the power of UIKit to your SwiftUI toolbox.
--
SwiftUI has spellbound an entire developer community since the introduction at WWDC 2019, and it is quite easy to understand why. It is fast, concise, and lets you build an entire working application with very few lines of code.
However, SwiftUI is still in its infancy and lacks many of the standard components we take for granted with more mature frameworks. Luckily, Apple’s engineers have developed ways to connect elements from UIKit straight into our SwiftUI applications. In this article, we look at how to leverage those mechanisms to create a SwiftUI wrapper for the good old UICollectionView.
A playground with code examples is available on Github.
What Do We Need?
Before we can connect a UIKit component to SwiftUI, we need to understand the contact surface between the two. The ways that the two frameworks are allowed to communicate with each other will significantly impact the way we write our code. Let’s start by looking at the protocol that enables us to create a wrapper in the first place.
UIViewRepresentable
The UIViewRepresentable protocol gives SwiftUI the possibility to create, manage, and dispose of UIKit components by declaring four useful methods.
makeUIView(context:)
This method creates and configures a new instance of the UIView you want to display in your application. We will use this to create a UICollectionView and set it up according to what we want it to do. The context parameter is aUIViewRepresentableContext
struct, which contains information about the current state of the system. We can use this to, for example, style our view based on whether Dark Mode is activated or not.makeCoordinator()
This method allows us to create a coordinator object which helps manage the interactions between the UIKit component, and the rest of the application. In our case, we will use it to implement delegate and data source methods for the collection view.updateUIView(_:content:)
As the name might suggest, we implement this method to make adjustments to our view when the application state changes in a way that affects our…