NSCollectionView Tutorial
In this NSCollectionView tutorial for macOS, you’ll learn how to add a collection view to your app and populate it with a data source – using Swift! By Gabriel Miro.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
NSCollectionView Tutorial
30 mins
- Getting Started
- The Starter Project Code
- Model
- Controllers
- Behind the Scenes of Collection Views
- Layouts
- The Collection View Items
- Supplementary Views
- The Collection View Data Source and Delegates
- Creating the Collection View
- Configure the Collection View Layout
- Creating a Collection View Item
- Add Controls to the View
- Add a CollectionViewItem to the Nib and Connect the Outlets
- Populate the Collection View
- Set the Data Source
- Troubleshooting
- Loading Items When the Model Changes
- Going Multi-Section
- Add Section Headers
- Implement the Data Source and Delegate Methods
- Sticky Headers
- Selection in Collection Views
- Where to Go From Here?
Sticky Headers
New to macOS 10.12 are the NSCollectionViewFlowLayout
properties sectionHeadersPinToVisibleBounds
and sectionFootersPinToVisibleBounds
.
When sectionHeadersPinToVisibleBounds
is set to true
, the header view for the topmost visible section will stay pinned to the top of the scroll area instead of being scrolled out of view. As you scroll down, the header stays pinned to the top until the next section’s header pushes it out of the way. This behavior is referred to as “sticky headers” or “floating headers”.
Setting sectionFootersPinToVisibleBounds
to true
behaves similarly, pinning footers to the bottom of the scroll area.
Open ViewController.swift and at the end of configureCollectionView()
add the line:
flowLayout.sectionHeadersPinToVisibleBounds = true
Build and run. Check Show Sections and scroll up a bit so the first row partially scrolls out of view.
Watch how the first section header is still visible and the first row shows through the section header.
NSCollectionViewFlowLayout
and overriding the layoutAttributesForElements(in:)
method. This is described in detail in our Advanced Collection Views in OS X Tutorial.
Selection in Collection Views
To show an item as selected, you’ll set a white border, non-selected items will have no border.
First, you need to make the collection view selectable. Open the Main.storyboard, select the Collection View and in the Attributes Inspector, check Selectable.
Checking Selectable enables single selection, meaning you can click an item to select it. When you choose a different item, it deselects the previous item and selects the item you just picked.
When you select an item:
- Its
IndexPath
is added to theselectionIndexPaths
property ofNSCollectionView
. - The
isSelected
property of the associatedNSCollectionViewItem
is set totrue
.
Open CollectionViewItem.swift. Add the following at the end of viewDidLoad()
:
// 1
view.layer?.borderColor = NSColor.white.cgColor
// 2
view.layer?.borderWidth = 0.0
- Sets white for the border when its width is greater than zero
- Sets
borderWidth
to0.0
to guarantee that a new item has no border — i.e, not selected
To set the borderWidth
each time the isSelected
property changes add the following code at the top of the CollectionViewItem
class:
override var isSelected: Bool {
didSet {
view.layer?.borderWidth = isSelected ? 5.0 : 0.0
}
}
Whenever isSelected
is changed, didSet
will add or remove the white border according the new value of the property.
isSelected
property is not always the right way to test whether an item is selected or not. When an item is outside the collection view’s visibleRect
the collection view isn’t maintaining an NSCollectionViewItem
instance for this item. If this is the case than the collection view’s item(at:)
method will return nil
. A general way to check whether an item is selected or not is to check whether the collection view’s selectionIndexPaths
property contains the index path in question.
Build and run.
Click an item and you’ll see highlighting. Choose a different image and you’ll see fully functional highlighting. Poof! Magic!
Where to Go From Here?
Download the final version of SlidesMagic here.
In this NSCollectionView tutorial, you went all the way from creating your first ever collection view, through discovering the intricacies of the data source API with sections, to handling selection. Although you covered a lot of ground, you’ve only started to explore the capabilities of collection views. Here are more great things to check out:
- “Data Source-less” collection views using Cocoa Bindings
- Different kind of items
- Adding and removing items
- Custom layouts
- Drag and drop
- Animations
- Tweaking
NSCollectionViewFlowLayout
- Collapsible Sections (new in macOS 10.12)
Some of these topics are covered in our Advanced Collection Views in OS X Tutorial.
The video, documents, and code in the list below are recommended to get an even better understanding of collection views:
- WWDC 2015 – Session 225 – What’s New in NSCollectionView
- AppKit Release Notes (OS X v10.11)
- AppKit Release Notes for macOS 10.12
- CocoaSlideCollection – Sample code of WWDC Session 225 above. Written in Objective-C
-
Exhibition – Sample code from Apple, written in Swift using
NSCollectionViewGridLayout
I wish you a pleasant journey with Collection View in your apps. I look forward to hearing your ideas, experiences and any questions you have in the forums below!