NSCollectionViewItem never instantiates

I lost a little here: I created a button acting like a colorPicker: clicking on it shows a collectionView in a popover. At first I did this with a nib file containing view + collectionView (built-in to scrollView + clipView). The material works great.

Since the nib file is very simple (and to improve my coding skills when developing representations programmatically), I decided to get rid of the nib file and write the missing part in the code. The thing is, I was able to do this job, except for the contents of the View collection. After deep research, it turns out that inside the method:

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

which should manage the data source, method

 collectionView.makeItem(withIdentifier: String, for: IndexPath) 

does not work. In fact, in:

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

the element is not initialized, as the debugger says when I enter (not zero, uninitialized ). Apparently, the makeItem method never instantiates any collectionViewItem from the subclass I made. The identifier is beautiful, and the collectionView.register function is called, as in the nib version, since both projects are identical at these points. The makeItem function simply does not call the loadView method of the NSCollectionViewItem subclass.

Any clue?

Josh

+3
swift macos nscollectionview
source share
1 answer

Using the collectionView.makeItem(withIdentifier:for:) method, you first need to either register the class or the nib file as a collection:

Class usage

Use register(_:forItemWithIdentifier:) ( register(_:forItemWithIdentifier:) first parameter accept AnyClass? )

 collectionView.register(MyCustomCollectionViewItemSubclass.self, forItemWithIdentifier: "SomeId") 

Using Nib File

Use register(_:forItemWithIdentifier:) ( register(_:forItemWithIdentifier:) first parameter accept NSNib? ).

 let nib = NSNib(nibNamed: "MyCollectionViewItem", bundle: nil)! collectionView.register(nib, forItemWithIdentifier: "SomeId") 

The main thing: in your Nib file, you also need to make sure that you add the NSCollectionViewItem to the scene. You must also set the class of the object in your subclass in order for it to work (you can set it in the inspector panel).

Hope this helps!

+2
source share

All Articles