I'm a bit lost here: I created a button acting like a colorPicker: clicking on it shows a collectionView in a popover. I first did it with a nib fil containing a view + the collectionView (embedded in as scrollView + a clipView). The stuff works just fine.
As the nib file is very simple (and to improve my coding skills in designing views programmatically), I decided to get rid of the nib file and write the missing part in code. The thing is, I manage to get the job done except for the content of the collectionView. After deep investigation, it appears that, inside the method:
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem
which is supposed to manage the data source, the method
collectionView.makeItem(withIdentifier: String, for: IndexPath)
doesn't work. In fact, in:
let item = collectionView.makeItem(withIdentifier: ColorPickerPopover.itemIdentifier, for: indexPath)
item is uninitialized, as the debugger says when I step in (not nil, uninitialized). Apparently, the makeItem method never instantiate any collectionViewItem from the subclass I've made. The identifier is fine and the collectionView.register function is called, just like in the nib version, as both projects are identical in these points. The makeItem function simply doesn't call the loadView method of the NSCollectionViewItem I've subclassed.
Any clue?
Josh
With the collectionView.makeItem(withIdentifier:for:)
method, you'll first need to either register the class or the nib file with the collection view:
Using a class
Use register(_:forItemWithIdentifier:)
(the first parameter accepts AnyClass?
)
collectionView.register(MyCustomCollectionViewItemSubclass.self, forItemWithIdentifier: "SomeId")
Using a Nib file
Use register(_:forItemWithIdentifier:)
(the first parameter accepts NSNib?
).
let nib = NSNib(nibNamed: "MyCollectionViewItem", bundle: nil)!
collectionView.register(nib, forItemWithIdentifier: "SomeId")
The key thing: On your Nib file, you also have to make sure that you have an NSCollectionViewItem
added to the scene. You also have to set the object's class to your subclass in order for it to work (you can set it on the inspector's panel).
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With