Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSCollectionView crashes when creating items

My NSCollectionView crashes when calling makeItem(withIdentifier identifier: String, for indexPath: IndexPath). numberOfItemsInSection returns the correct value. If I call makeItem... in viewDidLoad rather than in itemForRepresentedObject I see an error indicating that the indexPath is out of bounds. How can this be?

The collection view loads like this:

class TagCollectionViewController: NSViewController, NSCollectionViewDataSource {

  fileprivate static let itemIdentifier = "TagItem"

  @IBOutlet var collectionView: NSCollectionView!
  fileprivate var tags = List<Tag>.init()

  override func viewDidLoad() {
    super.viewDidLoad()

    let nib = NSNib(nibNamed: "TagCollectionViewItem", bundle: nil)
    collectionView.register(nib, forItemWithIdentifier: TagCollectionViewController.itemIdentifier)

    collectionView.dataSource = self
}

(The List collection is a Realm class)

During viewWillAppear() the tags collection is populated from a ReSwift state:

override func viewWillAppear() {
  for image in mainStore.state.selectedImages {
    for tag in image.tags {
      tags.append(tag)
    }
  }

  super.viewWillAppear()
}
like image 828
Rik Avatar asked Feb 04 '23 20:02

Rik


1 Answers

Solved it.

When I created the .xib for the item I added an NSCollectionViewItem object but didn't wire up the view to my custom view.

enter image description here

To recap, for anyone who gets caught out by this, the steps to creating a NSCollectionViewItem are:

  1. Create the nib and configure your views
  2. Add an NSCollectionViewItem object to your nib
  3. Wire up your view (and any other views) to the object
  4. Register the nib with the collectionView in your view controller
like image 91
Rik Avatar answered Feb 07 '23 18:02

Rik