Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c Cocoa-如何在集合视图中获取当前选定的对象?_Objective C_Cocoa - Fatal编程技术网

Objective c Cocoa-如何在集合视图中获取当前选定的对象?

Objective c Cocoa-如何在集合视图中获取当前选定的对象?,objective-c,cocoa,Objective C,Cocoa,我在cocoa应用程序中有一个NSCollectionView 我可以通过以下迂回方式在“集合”视图中获取有关当前选定对象的信息: NSIndexSet* index = [self.currentCollectionView selectionIndexes]; CardModel* card = [[self.currentCollectionView itemAtIndex:index.firstIndex] representedObject]; NSCollectionView类是否

我在cocoa应用程序中有一个
NSCollectionView

我可以通过以下迂回方式在“集合”视图中获取有关当前选定对象的信息:

NSIndexSet* index = [self.currentCollectionView selectionIndexes];
CardModel* card = [[self.currentCollectionView itemAtIndex:index.firstIndex] representedObject];

NSCollectionView
类是否有返回所选对象的方法?或者这是最好的方法吗?

如果你问
选择索引是否是访问
NSCollectionView
选择的唯一方法,答案是肯定的。

NSTableView
不同,你没有委托/通知,通知你选择。因此,
selectionIndexes
是一条出路

我不确定您是否为阵列控制器设置了观察员。但您显示的代码仅用于检索选定对象。要获得有关对象选择的通知,您需要为阵列控制器上的键路径
选择索引
(或IB中设置的任何内容)添加观察者

[myArrayController addObserver:self
       forKeyPath:@"selectionIndexes" 
       options:NSKeyValueObservingOptionNew
       context:nil];

-(void)observeValueForKeyPath:(NSString *)keyPath 
                     ofObject:(id)object
                       change:(NSDictionary *)change
                      context:(void *)context
{
    if([keyPath isEqualTo:@"selectionIndexes"])
    {
        // This will be invoked whenever objects are selected in Collection View.
        // Now collectionView selectionIndexes can be used to get the selected objects.
    }
}

一种方法是在xib中使用绑定。为要由集合中的视图表示的项设置NSArrayController。在xib中,在集合视图的绑定检查器中,将集合视图的内容绑定到
collectionViewArrayController.arrangedObjects
。还将选择索引绑定到
collectionViewArrayController.SelectionIndex
。现在,您可以在应用程序代理中创建阵列控制器的出口,并在那里访问所选对象

例如,声明
selectedCard
属性,以及连接到
collectionViewArrayController
collectionViewAC
插座属性。现在,您可以通过
selectedObjects
获得所需的卡片项目

- (id)selectedCard
{
    id selectedCards = [collectionViewAC selectedObjects];
    if ([selectedCards count]) {
        return [selectedCards objectAtIndex:0];
    }
    return nil;
}
使用绑定可以保持对所有内容的观察和更新