【问题标题】:how to detect a cell in uicollectionview didselect delegate method如何在 uicollectionview didselect 委托方法中检测单元格
【发布时间】:2013-01-17 20:55:06
【问题描述】:

我正在构建一个类似于 iPhone 照片应用的应用。我可以使用PSUICollectionView 在网格状视图中显示图像。当我点击集合视图的网格单元格时,应该会出现一个复选框图像。我的问题是当我使用以下代码时,我看到多个随机单元格填充了复选框图像。

- (void)collectionView:(PSUICollectionView *)collectionView didSelectItemAtIndexPath:     (NSIndexPath *)indexPath 
{
    NSLog(@"%@ - %d", NSStringFromSelector(_cmd), indexPath.item);
    ImageGridCell *cell = (ImageGridCell *)[collectionView cellForItemAtIndexPath:indexPath];
    UIButton *chkboxBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [chkboxBtn setFrame:CGRectMake(60, 60, 30, 30)];
    [chkboxBtn setImage:[UIImage imageNamed:@"Checkmark-iPhone.png"] forState:UIControlStateNormal];
    [cell addSubview:chkboxBtn];
}

【问题讨论】:

  • 任何帮助将不胜感激。

标签: ios uicollectionview uicollectionviewcell


【解决方案1】:

问题可能是您的自定义单元格没有实现prepareForReuse 方法。当一个单元格被重复使用时,它可能有也可能没有复选框,这取决于复选框是否是在之前的使用中添加的。

解决此问题的几种方法。一种简单的方法是在ckhboxBtn 中添加标签,然后在prepareForReuse 方法中删除chkboxBton。例如,添加复选框时,添加以下内容:

[chkboxBtn setTag:100];

然后在您的UICollectionViewCell 类实现中,添加/扩展prepareForReuse 方法:

-(void)prepareForReuse{
    [[self viewWithTag:100] removeFromSuperview];
}

【讨论】:

  • 这是否也适用于 UITableViewCells?
  • 是的,它现在正在从其他随机单元格中删除复选框,这些单元格已被 uicollectionview 重用。但问题是现在复选框甚至从选定的单元格中都被删除了。
  • @SubhenduKumarMukherjee - 您需要跟踪已选择的单元格,并在 collectionView:cellForItemAtIndexPath: 中为已选择的单元格放置复选框。
  • @jhilgert00 - 是的,prepareForReuse 适用于UITableViewCell。见developer.apple.com/library/ios/documentation/uikit/reference/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-24
  • 1970-01-01
  • 2020-02-02
  • 2015-05-10
  • 1970-01-01
  • 2012-09-22
相关资源
最近更新 更多