我对以下代码有疑问:
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 ,我无法连接它?
编辑
找到了找到父(抽象)子类的导出的方法:
编辑
使用父子类实现的解决方案:
- (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;
}
最佳答案
问题很简单,编译器只知道 cell
是 UICollectionViewCell *
并且该类型没有属性 x
.因此,您需要向编译器提供所需的信息。一种方法是从包含属性 x
的某些常见父类(super class)中派生两种细胞类型。 ,然后将该类型用于您的 cell
伊瓦尔一种更简单的方法是声明具有该属性的协议(protocol),并在您的单元格类型中采用该协议(protocol)。然后您可以简单地将单元指定为采用该协议(protocol)的标准单元,如下所示:
UICollectionViewCell<MyProperty> *cell;
关于iOS 返回不同的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22888451/