Get view index inside NSCollectionView?

I developed an application for Mac OS X Lion using my new NSTableView based on presentation, but since I want to port the entire application to Snow Leopard, I am trying to find a better way to imitate this kind. So far I have created an NSCollectionView, and everything is fine, except that I cannot get the view index from which the button click event is fired. In Lion, I have the following function:

- (IBAction)buttonClick:(id)sender 

so I can get the view index inside the tableview using a method (I cannot remember its name), for example

 - (NSInteger)rowForView:(NSView *)aView 

when aView is the sender's supervisor, but I could not find something like this to represent the collection ... The only "useful" method seems

 - (NSCollectionViewItem *)itemAtIndex:(NSUInteger)index 

(or something like this), but it cannot help me, since it returns an NSCollectionViewItem, and I can’t even access it, knowing only the corresponding view!

+7
source share
5 answers

Inside buttonClick try this code:

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

Hope this helps :)

+4
source

Geesh! Both of these approaches have problems. I see how the first one can work, but note that "collectionViewItem" is actually a view, not a collectionViewItem, which is the view controller.

The second method will not work unless you subclass the button and set a backlink to collectionViewItem. Otherwise, your view does not know what the collectionViewItem control is in control of. Instead, you should use the selector binding to collectionViewItem createdObject to get the action on the correct object in your array.

+2
source

How about something like:

 id obj = [collectonViewItem representedObject]; NSInteger index = [[collectionView contents] indexOfObject:obj]; 
+1
source

As I suggested here: How to handle button clicks from NSCollectionView

I would do it like this (because the button you want to click must be associated with the corresponding model, so the object presented):

  • Add a method to the model of your collectionViewItem (e.g. buttonClicked)
  • Bind the Target Button to Collection item.
  • When binding the specified model key path to: the represented object
  • When binding set selectorname to: methodname that you selected earlier (e.g. buttonClicked)
  • Add a protocol to your model if you must inform the delegate or install an observer template
0
source
  • use NSArrayController to bind to an NSCollectionView,

  • use the collectonViewItem.representedObject command to get the custom model you define.

  • save and get the index in your custom model.

This works for me.

0
source

All Articles