【问题标题】:How to fix an Incompatible pointer for subclass of UICollectionViewCell如何修复 UICollectionViewCell 子类的不兼容指针
【发布时间】:2014-06-28 00:11:49
【问题描述】:

我已经实现了UICollectionViewCell 的一个子类SPCell,我用它来在我的UICollectionViewController 中创建单元格。现在,当我收集一个单元格时,为了对其进行处理,我收到了一个警告Incompatible pointer types initializing 'SPCell *' with an expression of type 'UICollectionViewCell *'

这是一个例子。我的自定义单元格包含一个图像,我想更改它的 alpha 值。但是在我分配单元格的行中,我收到了这个警告。

- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath;{  
    SPCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
    cell.thumbnail.alpha=0.6;
}

提前致谢。

【问题讨论】:

  • SPCell *cell = (SPCell *)[self.collectionView cellForItemAtIndexPath:indexPath];

标签: ios objective-c uicollectionviewcell incomplete-type


【解决方案1】:

你只需要添加一个强制转换让编译器知道你在做什么 -

- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath;{  
    SPCell *cell = (SPCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    cell.thumbnail.alpha=0.6;
}

【讨论】:

  • 太棒了,我认为没有必要,因为SPCell 实现了UICollectionViewCell 的子类。但效果很好,谢谢。
  • 不,您可以安全地将子类实例分配给超类变量 - UICollectionViewCell *cell=mySPCellInstance,因为所有 UICollectionViewCell 方法和属性都将可用。您不能将超类分配给子类变量,因为子类属性和方法可能不可用 - 如果您包含强制转换,那么编译器会信任您(尽管如果您弄错了事情会在运行时爆炸)
猜你喜欢
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多