Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Get represented object in NSCollectionView Item View action

Here's what I have:

Now, the question:

When the user clicks the button, how could I tell which is the represented object? (the item attached to that particular view where the button belongs)

P.S. I can obviously do something like:

NSInteger itemIndex = [[_collectionView subviews] indexOfObject:[sender superview]];
MyItem item = _items[itemIndex];

But it doesn't look good at all - although it does work.

Ideas?

Upvotes: 0

Views: 856

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90711

You don't say what object is the target of the button's action. You can do this several ways.

For example, you can use a custom subclass of NSCollectionViewItem. You would target the button's action to the collection view item. Then, the collection view item would directly consult its own representedObject property. If necessary, it could then call another object (e.g. window controller) with the necessary information. Or just invoke a method on the represented object, if that's appropriate.

Similarly, you could use a custom view class as the collection view item's view. That view class could have an outlet connected to its collection view item. The button would be targeted to an action method on that view class, which would get the collection view item from its outlet and then get the representedObject from the collection view item.

Another approach is to use bindings for the button. You can bind its target (which includes specifying a selector) and you can also bind an argument to be passed to the selector. You could bind the target to the collection view item (File's Owner in the collection view item view NIB) with model key path representedObject. Then, the button targets the represented object directly.

Or, you could bind the button's target to something else and bind the argument to the collection view item, model key path representedObject. So, the button will call a method on an object and pass the represented object as the argument to that method.

Upvotes: 1

Related Questions