Reputation: 551
I am currently developing an OS X application with Swift. I am trying to use an NSCollectionView
in my main view, and so I have added an NSCollectionView
object to my .xib
file. I haven't changed anything in regards to that other than linking the data source and delegate to the File's Owner.
This is the code I have written to implement the NSCollectionViewDataSource
protocol:
/// MARK: - NSCollectionViewDataSource
extension MainViewController: NSCollectionViewDataSource {
func collectionView(collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(collectionView: NSCollectionView, itemForRepresentedObjectAtIndexPath indexPath: NSIndexPath) -> NSCollectionViewItem {
let itemView = collectionView.makeItemWithIdentifier("fileItem", forIndexPath: indexPath)
itemView.textField!.stringValue = "TEST"
return itemView
}
}
Now, when I run my code, I am getting an uncaught exception, and the application crashes, and I am not sure why. Here is part of the stack trace that I think is useful:
2016-04-02 18:58:02.768 Pilot[5442:679789] *** Assertion failure in -[NSCollectionView setItemPrototype:], /Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1404.46/Binding.subproj/NSCollectionView.m:1286
2016-04-02 18:58:02.971 Pilot[5442:679789] An uncaught exception was raised
2016-04-02 18:58:02.971 Pilot[5442:679789] Use -registerNib:forItemWithIdentifier: and -registerClass:forItemWithIdentifier: with new CollectionViews
Any help would be greatly appreciated.
Upvotes: 1
Views: 1494
Reputation: 32163
You have to register custom views like this:
collectionView.register(MyFileCollectionViewItem.self, forItemWithIdentifier: "fileItem")
before loading any items into the collection view (I recommend in the same block it's created, or in viewDidLoad()
of its controller).
Upvotes: 1