Getting model from click on NSCollectionVIew item

折月煮酒 提交于 2019-12-24 05:28:08

问题


I'm trying to put up a basic app with a tabbed interface, and it's been a few years since I've done any cocoa development so I'm rusty... My app will use tabs, and display a default view of items when you load a tab, allowing you to click on one of the items to swap in a view for that item (think chrome, when you open a new tab and it displays your favorite sites which you can click on to open).

Currently I have implemented a basic single window UI for this almost entirely in interface builder. A window with an NSCollectionView, using bindings with an ArrayController and NSMutableArray of collection items in my window controller. Works great.

There are two things, however, I'm not sure about and it makes me wonder if I'm better off doing things programmatically here instead of messing with Interface Builder. Specifically the two things I'm not sure how to do:

  1. Get click events on the NSCollectionView and map that to the model the clicked on item represents.
  2. Load new instances of this collection view in new tabs (a user could open up multiple tabs all of which should display the grid of items)

For #1 I don't really see a great way to do this. I can capture mouseDown in the window controller, but I have no idea how to map that back to the model. I also created a NSView subclass for my collection view item, however I can't figure out a way to map that view to the model either...

For #2 I don't think there's a great way to do this, other than creating the views programmatically. The only other thought I had was to put the view in another .xib and use that to create new views when needed. Which would probably work fine if I could figure out #1...

So, am I better off just creating the collection view programmatically or is there something I can do here?


回答1:


For the sake of others, here's what I ended up doing... This works though I suspect it may not be ideal.

I created an ItemView which was a subclass of NSView and set the class of my Collection View Item to that. Then in that class I did the following:

- (void) mouseDown: (NSEvent *) theEvent
{
    NSCollectionView *myCollectionView = (NSCollectionView *)[self superview];
    NSInteger index = [[myCollectionView subviews]  indexOfObject:self];
    Room *room = [[myCollectionView content] objectAtIndex:index];
    AppDelegate *appD = (AppDelegate *)[[NSApplication sharedApplication]delegate];
    [appD.windowController loadRoom: room];
}



回答2:


NSCollectionViewItem is a subclass of NSViewController, on which you can set/get the representedObject. I always use that for access to the underlying object.

⑵ You absolutely want to split up your XIBs. Every time I’ve done it, I find it’s made my job easier.



来源:https://stackoverflow.com/questions/21805887/getting-model-from-click-on-nscollectionview-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!