Search code examples
cocoaindexingnstableviewnscollectionviewnscollectionviewitem

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!


Solution

  • Within buttonClick, try this code:

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

    Hope this helps :)