我有一个特定的 UICollectionViewCell
,我想实例化自己,然后添加到 UICollectionView
。为了使其工作,UICollectionViewCell
实例需要设置其 .reuseIdentifier
属性。
通常,描述单元格的类或 Nib 会在 Collection View 中注册,并且 Collection View 会使用已设置的 .reuseIdentifier
实例化单元格,方法如下:
- registerClass:forCellWithReuseIdentifier:
- registerNib:forCellWithReuseIdentifier:
但是,由于我是在 Collection View 之外构建此单元格,因此这些不适用。
当我自己创建单元格时,似乎无法设置它的 .reuseIdentifier
(因为它是一个只读属性,并且没有初始化它的 init...
方法)。
当没有设置.reuseIdentifier
时,UICollectionView
在添加单元格时会抛出异常。此行为不同于 UITableView
,其中重用标识符是可选的。
设置 Collection View 单元格重用标识符的简单解决方法是将其嵌入到 .xib
文件中并使用 Identifier
框,然后创建单元格实例
[NSBundle.mainBundle loadNibNamed:@"MyCellName" owner:self options:nil][0];
然后我可以传递上面实例化的 UICollectionViewCell
,一切正常。
...但这似乎是一个非常愚蠢和武断的圈套,可以跳过。有没有其他方法可以在没有 .xib
-wrapper 绕行的情况下在单元格实例上设置此属性?
更新:Apple 的文档是这样说的:
To simplify the creation process for your code, the collection view requires that you always dequeue views, rather than create them explicitly in your code.
...这实际上不是真的,因为它不需要这个(即,外部实例化的单元格工作正常,只要它们的标识符设置以某种方式,例如,如果从 .xib
加载),并且在我的特定用例中它也没有“简化我的代码的创建过程”(而是需要一个额外的文件;此外,要求 Collection View 创建这些几个复杂的一次性文件会很麻烦)。
但上面的内容似乎确实暗示问题的答案是否定的:除非让 Collection View 将其出列,否则有意“难以”创建可用的单元格。
最佳答案
很抱歉这么说,但我认为您将不得不接受 UICollectionView 是生产 UICollectionViewCells 的唯一 Apple 品牌工厂这一事实。因此,如果您有两个 Collection View ,您希望在其中显示完全相同的对象,那您就不走运了!
好消息是,如果您有两个 Collection View ,您希望在其中显示一个单元格,该单元格看起来与另一个完全相同,那么您就可以完成任务。很简单:
@interface MyModelClass : NSObject
// a bunch of data
@end
@interface MyCollectionViewCell : UICollectionViewCell
-(void)refreshCellWithObject:(MyModelClass *)object;
@end
同时,在拥有 UICollectionView cv1 和 cv2 的任何类中
[[self cv1] registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"MyCollectionViewCell"];
和
[[self cv2] registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"MyCollectionViewCell"];
而且他们的数据源可以看起来一样
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
MyModelObject *obj = [self theObjectIWant];
MyCollectionViewCell *cell;
cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCollectionViewCell" forIndexPath:indexPath];
[cell refreshCellWithObject:obj];
return cell;
}
关于objective-c - 在 UICollectionViewCell 上设置 .reuseIdentifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13281631/