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
, use NSNib
to instantiate the item yourself (factory method below). In the method call, you can specify self
as the owner, and it will hook up the outlets for you. Then set representedObject
and fiddle with the image view. Here's code for the factory method:
// Load item view from CustomItem.nib
// For consistent results, nib should contain exactly one NSCollectionViewItem.
- (NSCollectionViewItem *)newCollectionViewItem {
static NSNib *nib;
if (!nib) nib = [[NSNib alloc] initWithNibNamed:@"CustomItem" bundle:nil];
NSArray *nibObjects;
if (![nib instantiateNibWithOwner:self topLevelObjects:&nibObjects]) return nil;
for (id obj in nibObjects)
if ([obj isKindOfClass:[NSCollectionViewItem class]])
return (NSCollectionViewItem *)obj;
return nil;
}
After you call [super newItemForRepresentedObject:]
, check if you need to keep the image view. If you do, instantiate a new NSImageView
, 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.