I feel this being a simple task, but I don't seem to be able to make it work. I'm trying to have a NSCollectionView with custom items. I added another NSImageView to the custom view of the item, and I subclassed this view in order to add the custom outlet connected to this additional NSImageView.
Now I am overriding - (NSCollectionViewItem *)newItemForRepresentedObject:(id)object
because sometimes I need to remove this NSImageView.
- (NSCollectionViewItem *)newItemForRepresentedObject:(id)object {
CustomItem *theItem = (CustomItem *)[super newItemForRepresentedObject: object];
...
if (I need to remove that NSImageView) {
[[theItem additionalImageView] removeFromSuperview];
}
return theItem;
}
Anyway, additionalImageView seems to be (nil)
. This is someway obvious because the super method will return the default NSCollectionViewItem which has not the custom outlet.
What's the best thing to do right here? I read something about the copy
method, and I tried with:
- (NSCollectionViewItem *)newItemForRepresentedObject:(id)object {
CustomItem *theItem = [(CustomItem *)[super itemPrototype] copy]; // Here is the change
...
if (I need to remove that NSImageView) {
[[theItem additionalImageView] removeFromSuperview];
}
return theItem;
}
But this is not going to work. So, is there a way to preserve custom outlets when using a custom NSCollectionViewItem?
Any help would be very appreciated. Thank you!
The problem is that no one will instantiate the new item's image view. Copy won't work, since you need two image views, not one.
There are two ways to handle this:
Instead of calling the superclass implementation of
newItemForRepresentedObject
, useNSNib
to instantiate the item yourself (factory method below). In the method call, you can specifyself
as the owner, and it will hook up the outlets for you. Then setrepresentedObject
and fiddle with the image view. Here's code for the factory method:After you call
[super newItemForRepresentedObject:]
, check if you need to keep the image view. If you do, instantiate a newNSImageView
, set its properties, and add it to the superview. That last part sounds tricky. Maybe someone who's taken that approach will provide some code.One way to solve the problem is to create 2 different prototype views and bind them to your controller. Now when you are in the
newItemForRepresentedObject
you can set theview
of yourNSCollectionViewItem
with a copy (using theNSCoding
protocol) of the appropriate prototype depending on the object. I use theNSCollectionViewItem
I get from super.Here My sample code for the casa of showing a string or a number attribute editor of an unknown
NSManagedObject
,NSManagedAttribute
is a utility class that I use as represented object for my collection view and keeps information about the attribute/relationshipIt is working for me :-)