为什么添加到uicollectionview单元格的视图不会出现在选择期间添加的视图

时间:2014-09-23 06:32:41

标签: ios objective-c uicollectionview uicollectionviewcell

我在选择和重新加载项目上添加了一个collectionView cell视图,但视图在第一个选择中不可见,其仅在再次单击单元格时可见。首次加载collectionView后,在第一次选择collectionView单元格时,添加的视图正在添加但不可见,大小增加,只有第二次选择后才能看到视图。

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
 selectedIndexPath = indexPath;
  PastPicksGameCollectionViewCell *cell = (PastPicksGameCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(50,122, 150, 120)];
[view setBackgroundColor:[UIColor blueColor]];
[cell.contentView addSubview:view]
   [pastPicksGameCollectionView reloadItemsAtIndexPaths:@[selectedIndexPath]];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout  *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
if ([indexPath isEqual:selectedIndexPath]) {
    return CGSizeMake(320, 200);
}
return CGSizeMake(300, 120);
}

1 个答案:

答案 0 :(得分:0)

我认为reloadItemsAtIndexPaths:对你不利:它导致collectionView丢弃与该项相关联的单元格(即刚刚添加了子视图的单元格),并从队列中加载一个新单元格(该项目没有子视图。将丢弃的单元放置在队列上以供重用。再次单击时,会发生同样的事情。但是这一次,最初丢弃的单元格(确实有子视图)被重新使用,因此被显示出来。

就个人而言,我会避免将子视图添加到这样的单元格中 - 我会添加一个"永久性" UIView属性到您的自定义单元格类,然后您可以在didSelectItemAtIndexPath中使用它。但是您必须在cellForItemAtIndexPath中确保重置它(例如使用if (indexPath isEqual:selectedIndexPath) { create/show the subview } else { hide the subview/set to nil) }