ios - 如何让两个自定义 UICollectionViewCell 类共享相同的变量名

标签 ios objective-c swift oop uicollectionview

我有两个自定义 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/

相关文章:

iphone - 将 UIScrollView 手势识别器添加到另一个 UIScrollView

ios - 使用图像作为带有 Storyboard 的静态表格 View 的背景

ios - 从本地路径 URL 设置 UIimage - 导致崩溃

objective-c - 更改 block 内 NSString 的值

objective-c - 将光标悬停在图像上?

ios - 如何让 UICollectionView 单元格可以在其 setSelected : method? 中被多选

iphone - 如何使用 Objective-C 在 iPhone 中查看未接来电?

swift - 嵌套合并运算符的混淆

ios - SwiftUI 将数据从 View 传递到模态不会正确更新

swift - 是否可以将通用协议(protocol)传递到构造函数中以在 Swift 3 中进行适当的依赖注入(inject)?