因为你的单元格的内容是相同的,即,
- 图像视图
- 标题的UILabel
- UILabel 描述
除了创建一个抽象类然后将它们子类化,你还可以做的是,你只需创建一个 UICollectionViewCell 的自定义类,例如将其命名为 GenericCollectionViewCell,现在这个类应该有两个 nib 文件,并确保你为它们分配不同的重用标识符和不同的文件名当然,例如
- iPhoneCell
- iPadCell
所以,现在基本上你有 GenericCollectionViewCell.h 和 IBOutlets 到两个不同的 nib。
您必须在 GenericeCollectionViewCell 中创建一个 ENUM,例如
typedef NS_ENUM(NSUInteger, CellType) {
CELLIPHONE = 0,
CELLIPAD = 1
};
您将使用此 ENUM 进行初始化,例如该单元格使用什么类型的 nib,例如
+ (UINib*)cellNibForCellType:(CellType)cellType{
switch (cellType) {
case CELLIPHONE:
cellNib = [UINib nibWithNibName:@"IPhoneCollectionViewCell"
bundle:nil];
break;
case CELLIPAD:
cellNib = [UINib nibWithNibName:@"IPadCollectionViewCell"
bundle:nil];
break;
}
完成此操作后,您需要在 ViewController 的 viewDidLoad 中注册此单元格,
- (void)viewDidLoad
{
[super viewDidLoad];
[_collectionView registerNib:[GenericCollectionViewCell cellNibForCellType:CELLIPHONE] forCellWithReuseIdentifier:@"iPhoneCell"];
[_collectionView registerNib:[GenericCollectionViewCell cellNibForCellType:CELLIPAD] forCellWithReuseIdentifier:@"iPadCell"];
}
然后你可以继续@Greg 上面解释的内容,
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
GenericCollectionViewCell *cell = nil;
if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) {
// Make sure it match storyboard identifier for iPad cell
cell = [cv dequeueReusableCellWithReuseIdentifier:@"iPadCell" forIndexPath:indexPath];
}
else { //iPhone device
cell = [cv dequeueReusableCellWithReuseIdentifier:@"iPhoneCell" forIndexPath:indexPath];
}
cell.imageView.image = ...;
cell.title = ...;
cell.description = ...;
return cell;
}
基本上这是我想出来的,如果单元格的内容相同,那么制作超类有什么意义,我的意思是我不知道我可能错了。