iOS 返回不同的子类

标签 ios objective-c uicollectionviewcell subclassing

我对以下代码有疑问:

 UICollectionViewCell *cell;

if (_peopleNotTasks == NO) {
    static NSString *CellIdentifier = @"TaskCollectionCell";
     cell = (TaskCollectionCell *)[cv dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
} else {
    static NSString *CellIdentifier = @"PeopleCollectionCell";
     cell = (PeopleCollectionCell *)[cv dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
}
//both cells have property x
//this does not work: 
cell.x = @"this is an awesome string";

return cell;

为什么这不起作用?

TaskCollectionCell 和 PeopleCollectionCell 都是 UICollectionViewCell 的子类.

预期:

访问 TaskCollectionCell 和 PeopleCollectionCell 的属性。

如果我在抽象类(现在是 TaskCollectionCell 和 PeopleCollectionCell 的父类(super class))中创建一个 socket ,我无法连接它?
enter image description here

编辑
找到了找到父(抽象)子类的导出的方法:

enter image description here

编辑
使用父子类实现的解决方案:
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
 ParentCell *cell;
if (_onlyUsersTasks == NO) {
    static NSString *CellIdentifier = @"TaskCollectionCell";
    cell = (TaskCollectionCell *)[cv dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
} else {
    static NSString *CellIdentifier = @"PeopleCollectionCell";
    cell = (PeopleCollectionCell *)[cv dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
}
cell.commonString = @"Thanks Jonathan";
return cell;
}

最佳答案

问题很简单,编译器只知道 cellUICollectionViewCell *并且该类型没有属性 x .因此,您需要向编译器提供所需的信息。一种方法是从包含属性 x 的某些常见父类(super class)中派生两种细胞类型。 ,然后将该类型用于您的 cell伊瓦尔一种更简单的方法是声明具有该属性的协议(protocol),并在您的单元格类型中采用该协议(protocol)。然后您可以简单地将单元指定为采用该协议(protocol)的标准单元,如下所示:

 UICollectionViewCell<MyProperty> *cell;

关于iOS 返回不同的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22888451/

相关文章:

ios - 当异步附加新项目时,UICollectionView 快速滚动在单元格中显示错误的图像

ios - NSLineBreakMode 枚举和向后兼容性

ios - iOS 13 和 14 上的 NSKeyValuePopPendingNotificationLocal 崩溃

ios - 在 TableView 中对文本字段使用 endEditing 时崩溃

ios - UIColor 获取色调 :saturation:brightness:alpha: returns NO

ios - 如何在 UICollectionViewCell 中使用详细信息披露按钮?

ios - 创建子类并覆盖 loadView() 时 UITableViewController.tableView=nil

objective-c - NSDictionary 和 EXC_BAD_ACCESS

objective-c - 如何在 iOS 中的文本上创建 "Embossed"效果?

ios - 如何在 swift ios 中调整 Collection View 单元格高度?