我觉得这是一个简单的任务,但我似乎无法使其发挥作用。
我正在尝试使用带有自定义项目的 NSCollectionView 。我向该项目的自定义视图添加了另一个 NSImageView,并对该视图进行了子类化,以便添加连接到该附加 NSImageView 的自定义插座。
现在我压倒一切- (NSCollectionViewItem *)newItemForRepresentedObject:(id)object
因为有时我需要删除这个 NSImageView。
- (NSCollectionViewItem *)newItemForRepresentedObject:(id)object {
CustomItem *theItem = (CustomItem *)[super newItemForRepresentedObject: object];
...
if (I need to remove that NSImageView) {
[[theItem additionalImageView] removeFromSuperview];
}
return theItem;
}
无论如何,additionalImageView 似乎是(nil)
。这在某种程度上是显而易见的,因为 super 方法将返回默认的 NSCollectionViewItem,它没有自定义插座。
在这里最好做什么?我读过一些关于copy
方法,我尝试过:
- (NSCollectionViewItem *)newItemForRepresentedObject:(id)object {
CustomItem *theItem = [(CustomItem *)[super itemPrototype] copy]; // Here is the change
...
if (I need to remove that NSImageView) {
[[theItem additionalImageView] removeFromSuperview];
}
return theItem;
}
但这是行不通的。所以,使用自定义 NSCollectionViewItem 时有没有办法保留自定义插座?
任何帮助将不胜感激。谢谢你!
问题是没有人会实例化新项目的图像视图。复制不起作用,因为您需要两个图像视图,而不是一个。
有两种方法可以处理这个问题:
-
而不是调用超类的实现newItemForRepresentedObject
, use NSNib
自己实例化该项目(下面的工厂方法)。在方法调用中,您可以指定self
作为所有者,它会为您连接插座。然后设置representedObject
并摆弄图像视图。这是工厂方法的代码:
// Load item view from CustomItem.nib
// For consistent results, nib should contain exactly one NSCollectionViewItem.
- (NSCollectionViewItem *)newCollectionViewItem {
static NSNib *nib;
if (!nib) nib = [[NSNib alloc] initWithNibNamed:@"CustomItem" bundle:nil];
NSArray *nibObjects;
if (![nib instantiateNibWithOwner:self topLevelObjects:&nibObjects]) return nil;
for (id obj in nibObjects)
if ([obj isKindOfClass:[NSCollectionViewItem class]])
return (NSCollectionViewItem *)obj;
return nil;
}
打电话后[super newItemForRepresentedObject:]
,检查是否需要keep图像视图。如果这样做,请实例化一个新的NSImageView
,设置其属性,并将其添加到超级视图中。最后一部分听起来很棘手。也许采用这种方法的人会提供一些代码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)