Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of a view inside a NSCollectionView?

I've developed an app for Mac OS X Lion using its new view-based NSTableView, but as I want to port the whole app to Snow Leopard I'm trying to figure out the best way to emulate such a tableview. So far I've created a NSCollectionView and everything is fine, except for the fact that I can't get the index of the view from which a button click event is triggered. In Lion I have the following function:

- (IBAction)buttonClick:(id)sender

so I can get the index of the view inside the tableview using a method (I can't remember its name) like

- (NSInteger)rowForView:(NSView *)aView

with aView being the sender's superview, but I couldn't find something similar for the collection view ... The only "useful" method seems to be

- (NSCollectionViewItem *)itemAtIndex:(NSUInteger)index

(or something like this), but this can't help me as it returns a NSCollectionViewItem and I can't even access it knowing only the corresponding view!

like image 211
Nickkk Avatar asked Oct 22 '11 15:10

Nickkk


2 Answers

Within buttonClick, try this code:

id collectionViewItem = [sender superview];
NSInteger index = [[collectionView subviews]  indexOfObject:collectionViewItem];
return index;

Hope this helps :)

like image 53
Devarshi Avatar answered Nov 07 '22 16:11

Devarshi


Geesh! Both of those approaches have issues. I can see how the first on may work, but note that the "collectionViewItem" is actually the view, NOT the collectionViewItem, which is a view controller.

The second way will not work, unless you subclass the button and put in a back link to the collectionViewItem. Otherwise, your view does not know what collectionViewItem controls it. You should use a selector binding to the collectionViewItem's representedObject instead, to get the action to the correct object in your array.

like image 2
Gordon Apple Avatar answered Nov 07 '22 17:11

Gordon Apple