Comparing NSCollectionView and UICollectionView #2
In this post, I will talk about the difference in preparing the content container for macOS and iOS respectively.
For those who came from the iOS world, UICollectionView has been a long time component since iOS 6. It is widely used to display contents that are in different layouts, e.g. grid, row-based, or any custom layout.
DataSource protocol is used provide the data and views required by a collection view. In iOS, there are two required methods to build the bare minimum of UICollectionView.
collectionView(UICollectionView, numberOfItemsInSection: Int)
collectionView(UICollectionView, cellForItemAt: IndexPath)
The first one is similar to the counterpart in macOS, but the second is a bit different.
collectionView(NSCollectionView, numberOfItemsInSection: Int)
collectionView(NSCollectionView, itemForRepresentedObjectAt: IndexPath)
It is quite obvious that the first API is used to indicate the number of cells or items in the section (default one session only). The second API is the one actually gathering data information and configure the view components.
From the method signature, you may notice the difference. iOS is creating the item quite directly, but macOS kind of create this weird thing called “Represented Object”. It is due to legacy support. NSCollectionView actually exists since macOS 10.5, while iOS version is built from scratch. There are a lot of learnings in creating the modern NSCollectionView APIs.
To simplify and visualize the development process, we generally create the container content using Interface Builder, which will be included into Nib files (saved as *.xib files).
In iOS, we also set a “bridge” called
Reuse Identifier. The Collection View has a mechanism to manage memory usage of multiple cells. The Data Source method will look for a cell stored in a pool with the
Reuse Identifier. In simple case, all the cells are having the same identifier. Each time, one cell is pulled out and configure the view components based on the backing data store content. It may setup different text fields or images to the cell display. This
Reuse Identifier will be registered to a chosen Nib file, and loads the default view components inside.
In macOS, however, the workflow is a bit different. It uses a
makeItem(withIdentifier identifier: String, for indexPath: IndexPath) method to create the item object. A simple but magic way to connect to the Nib file is by setting the identifier the same name as the Nib file. For example, an identifier of
MyItem will look for a nib file named
MyItem.xib and retrieve its content. For a quick demo, you can watch a YouTube video here.
I am taking a challenge to write a post every day for 180 days. The content will be related to my life as a father, entrepreneur, developer and trainer.
In porting apps from iOS to macOS, one would compare the similarities and port the code over. Since 2015 with OSX El…medium.com