Here's a step-by-step guide on how to get these painful things working properly in Xcode 7.3 on OS X 10.11 El Capitan.
-
Drag an
NSCollectionView
object into an existing storyboard or standalone nib. -
Select the
NSCollectionView
, and in the inspector, change Layout from Content Array (Legacy) to Flow. -
Configure the rest how you see fit.
-
Next, add a new
NSCollectionViewItem
subclass to the project, naming it something like MyCollectionViewItem. -
Check the box next to Also create XIB file for user interface. Two files will be created.
-
Open the .xib document.
-
Select the File's Owner placeholder object in the Document Outline. Then in the inspector, remove the custom class the File's Owner item is pointing to. This usually points to the class that is created along with the nib file, but because
NSCollectionView
doesn't like to play by the rules, we don't want it pointing to anything. -
Next, drag an
NSCollectionViewItem
object on the canvas from the Object Library. -
In the Identity inspector, enter the name of the class we previously removed from the File's Owner item. It should have the same name as the nib document.
-
Now add any outlets/actions and all that good stuff, and connect them in the Interface Builder UI.
-
Once all hooked up, open the file with the code that the
NSCollectionView
will be connected to. -
Add an outlet like so:
@IBOutlet var collectionView: NSCollectionView!
-
Connect the outlet in Interface Builder, and return to the code.
-
In the
viewDidLoad()
implementation, add the following:let nib = NSNib(nibNamed: "MyCollectionViewItem", bundle: nil) self.collectionView.registerNib(nib, forItemWithIdentifier: "MyCollectionViewItem") self.collectionView.delegate = self self.collectionView.dataSource = self
-
Also, be sure to conform to the
NSCollectionViewDelegate
andNSCollectionViewDataSource
protocols like so:class MyViewController : NSViewController, NSCollectionViewDelegate, NSCollectionViewDataSource { // View controller code here }
-
Now add just a few more bits of code:
func numberOfSectionsInCollectionView(collectionView: NSCollectionView) -> Int { return 1 // <- This depends on the data being displayed } func collectionView(collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { return self.someKindOfCollection.count // <- This depends on the data being displayed } func collectionView(collectionView: NSCollectionView, itemForRepresentedObjectAtIndexPath indexPath: NSIndexPath) -> NSCollectionViewItem { let collectionObject = self.someKindOfCollection[indexPath.item] let item = self.collectionView.makeItemWithIdentifier("MyCollectionViewItem", forIndexPath: indexPath) item.representedObject = collectionObject return item }
-
That should do it.
For number 13, it won't let me connect the CollectionView as an outlet in my ViewController.