I'm experimenting with the new NSCollectionView
API, introduced in El Capitan.
Following the WWDC video, I create a subclass of NSCollectionViewFlowLayout
to determine the layout of the collection view.
class Layout : NSCollectionViewFlowLayout {
override func prepareLayout() {
super.prepareLayout()
self.minimumInteritemSpacing = 0
self.minimumLineSpacing = 0
let cheight = self.collectionView!.bounds.height
let cwidth = self.collectionView!.bounds.width
self.itemSize = CGSizeMake(cwidth / 2.0, cheight / 6.0)
}
}
After that, I've created a NSObject
subclass to serve as data source.
class DataSource : NSObject, NSCollectionViewDataSource {
func collectionView(collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(collectionView: NSCollectionView, itemForRepresentedObjectAtIndexPath indexPath: NSIndexPath) -> NSCollectionViewItem {
/* DOESN'T GET CALLED! */
let item = collectionView.makeItemWithIdentifier("cell", forIndexPath: indexPath)
item.view.wantsLayer = true
item.view.layer?.backgroundColor = NSColor.redColor().CGColor
return item
}
}
The issue is that collectionView:itemForRepresentedObjectAtIndexPath:
never gets called.
This is how I initialise the collection view:
let collectionView = NSCollectionView(frame: view.bounds)
let dataSource = DataSource()
let layout = Layout()
collectionView.collectionViewLayout = layout
collectionView.registerClass(NSCollectionViewItem.self,
forItemWithIdentifier: "cell")
collectionView.dataSource = dataSource
collectionView.backgroundColors = [.blackColor()]
I can clearly see the collection view in its superview, but there are no cells.
Also, this line, if called outside the delegate (but after the cell class is registered) makes the app crash!
let item = collectionView.makeItemWithIdentifier("cell", forIndexPath: /*any index path*/)
Am I doing something wrong or is NSCollectionView
new API broken?
Thanks.