spacecash21
spacecash21

Reputation: 1331

Cant get NSCollectionView NSCollectionViewItem to work

    override func viewDidLoad() {
    super.viewDidLoad()
    // Do view setup here.

    let item = NSNib(nibNamed: NSNib.Name("CollectionViewItem"), bundle: nil)
    self.collectionView.register(item, forItemWithIdentifier: .collectionViewItem)


extension ViewController: NSCollectionViewDataSource {

func numberOfSections(in collectionView: NSCollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
    return Templates.count
}

func collectionView(_ collectionView: NSCollectionView,
                    itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {

    let item = collectionView.makeItem(
        withIdentifier: .collectionViewItem, for: indexPath)

    guard let collectionViewItem = item as? CollectionViewItem else {return item}

    collectionViewItem.imageView = image
    return item
}
}

extension NSUserInterfaceItemIdentifier {
static let collectionViewItem = NSUserInterfaceItemIdentifier("CollectionViewItem")
}

I have set up everything as in the code below, but for some reason I can't get pass the

guard let collectionViewItem = item as? CollectionViewItem else {return item}

The guard always returns item, not the collectionViewItem. Maybe someone has encountered an issue like this? What am I doing wrong? Pretty much have been following the tutorial https://www.raywenderlich.com/1246-collection-views-in-os-x-tutorial.

Using the latest Xcode 10.0 + latest swift

Upvotes: 1

Views: 818

Answers (1)

spacecash21
spacecash21

Reputation: 1331

Found the problem.

Problem: What I did: I created a new file with subclass of NSCollectionViewItem and I choose to create .xib as well.

Turns out, Xcode 10.0 does not do this properly. It created a .xib with placeholders, File's owner and stuff. Xcode did not add Collection View Item object from IB. Which is strange, as previous versions did add the Collection View Item object automatically.

Once I added the Collection View Item object and set the class, problem solved itself.

Upvotes: 3

Related Questions