1

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.

Rohan
  • 541
  • 1
  • 11
  • 24
  • 1
    Did you register the "fileItem" with either registerNib or registerClass? Or otherwise created/wired it in the .xib file? – PRB Apr 03 '16 at 03:19
  • @PRB I did not register "fileItem" anywhere. This might be the problem. I'm not exactly sure what that parameter means and how I should register it. – Rohan Apr 04 '16 at 17:17
  • 1
    If you used the storyboard to design your layout, there should be a Collection View Cell inside the Collection View. Go to the Attributes Inspector (on the right side, Utilities view of the Storyboard), and give the cell the identifier "fileItem" (under Collection Reusable View) – PRB Apr 05 '16 at 12:18
  • 1
    If you used a separate NIB for your cell, you'll need something like this in your ViewDidLoad() fn for the view controller: // Load the Cell descriptor and register it with the CollectionView let collectionCellNib = UINib(nibName: "CollectionViewCell", bundle: nil) collectionView?.registerNib(collectionCellNib, forCellWithReuseIdentifier: collectionViewCellIdentifier) – PRB Apr 05 '16 at 12:19

1 Answers1

1

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).

Ky -
  • 30,724
  • 51
  • 192
  • 308