我有两个自定义 UICollectionViewCell
类,但是,我想在相同范围内创建一个具有相同名称的变量,因为所有属性和所有代码都在 cellForItemAtIndexPath
两个自定义单元格的方法相同。
我想做这样的事情: 例如:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CustomCell1/CustomCell2 *cell;
if (condition) {
cell = (CustomCell1 *)[collectionView dequeueReusableCellWithReuseIdentifier:kCustomCell1Identifier forIndexPath:indexPath];
} else {
cell = (CustomCell2 *)[collectionView dequeueReusableCellWithReuseIdentifier:kCustomCell2Identifier forIndexPath:indexPath];
}
// Remaining code is same for both custom cells
cell.property1 = value1;
cell.property2 = value2;
.
.
.
.
.
//lot of code
cell.property100 = value100;
return cell;
}
我这样做的目的是不想重复所有剩余的代码。我知道创建通用自定义单元格类并在该通用类中编写此条件可能是解决方案,但我如何才能在该类初始化之前将条件变量传递给自定义类。因为我认为我们无法初始化 (alloc init) UICollectionViewCell。
条件(三元)运算符是否可行?
最佳答案
您可以创建一个基础(父)collectionviewCell 类
@interface BaseCollectionViewCell : UICollectionViewCell
//Add the common methods(can add common IBOulet and IBAction) and implement them.
@end
现在您可以创建从 BaseCollectionViewCell 派生的新 Collection View 单元格:
@interface ChildCell : BaseCollectionViewCell
//add methods which are specific to the ChildCell as the methods of
//BaseCollectionViewCell is already available via inheritance.
@end
创建另一个 Collection View 单元格的方式相同:
@interface ChildCell2 : BaseCollectionViewCell
//add methods which are specific to the ChildCell2 as the methods of
//BaseCollectionViewCell is already available via inheritance.
@end
现在 ChildCell 和 ChildCell2 获得了 BaseCollectionViewCell 的所有方法。
将您的 Collection View 单元格与单独的重用标识符一起注册到这些类。 使用以下代码使单元格出队。
BaseCollectionViewCell *cell;
if (condition) {
ChildCell *cell1 = (ChildCell *)[collectionView
dequeueReusableCellWithReuseIdentifier:kCustomCell1Identifier
forIndexPath:indexPath];
//call cell1's specific properties if needed.
cell = (BaseCollectionViewCell *) cell1;
} else {
ChildCell2 cell2 = (ChildCell2 *)[collectionView
dequeueReusableCellWithReuseIdentifier:kCustomCell2Identifier forIndexPath:indexPath];
//call cell2's specific properties if needed.
cell = (BaseCollectionViewCell *) cell2;
}
//call common methods here.
关于ios - 如何让两个自定义 UICollectionViewCell 类共享相同的变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40040208/