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.

Leave a rating/review
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

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.

CV-StickyHeaders

Watch how the first section header is still visible and the first row shows through the section header.

Note: If your app needs to support OS X 10.11 as well, you will need to implement sticky headers “manually” by creating a subclass of 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.

SelectionAttributes

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:

  1. Its IndexPath is added to the selectionIndexPaths property of NSCollectionView.
  2. The isSelected property of the associated NSCollectionViewItem is set to true.

Open CollectionViewItem.swift. Add the following at the end of viewDidLoad():

// 1
view.layer?.borderColor = NSColor.white.cgColor
// 2
view.layer?.borderWidth = 0.0
  1. Sets white for the border when its width is greater than zero
  2. Sets borderWidth to 0.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.

Note: The 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.

ShowSelection

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:

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!

Gabriel Miro

Contributors

Gabriel Miro

Author

Zoltán Matók

Tech Editor

Chris Belanger

Editor

Michael Briscoe

Final Pass Editor and Team Lead

Over 300 content creators. Join our team.