【发布时间】:2017-03-08 02:01:20
【问题描述】:
我有一个 UICollectionView,我从我的 cellForItemAtIndexPath 中添加了 12 个单元格。当我滚动查看向下单元格时,所有功能都被保留,但是当我再次滚动向上时,某些单元格不会执行在 didSelectItemAtIndexPath 中加载的函数。
我设置了禁用某些行。但不是我点击的那一行 为什么会这样?重用单元可能是一个糟糕的准备吗?
我正在尝试重用功能,但这只会影响将单元格绘制错误或在另一个位置上,并且在 didSelectItemAtIndexPath 中添加的功能不起作用:
[self.myCollectionView reloadData];
[self.myCollectionView layoutIfNeeded];
NSArray *visibleItems = [self.myCollectionView indexPathsForVisibleItems];
NSIndexPath *currentItem = [visibleItems objectAtIndex:0];
NSIndexPath *nextItem = [NSIndexPath indexPathForItem:currentItem.item + 1 inSection:currentItem.section];
[self.myCollectionView scrollToItemAtIndexPath:nextItem atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
当我滚动并单击一个单元格时,这不会打开我的 secondViewController,我认为该单元格的索引错误已被禁用。
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyViewController *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath];
switch ([indexPath row]) {
case 0:
titleCell= @"Title0";
detailCell=@"Detail0";
if([indexPath row]==2){
[cell setUserInteractionEnabled:NO];//Here I set disable Could be the problem caused by this??
}
[cell.image setHidden:YES];
cell.image.contentMode = UIViewContentModeScaleAspectFit;
break;
//Here other cases with the same structure
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
[collectionView deselectItemAtIndexPath:indexPath animated:NO];
MySecondClass *secondClass = [self.storyboard instantiateViewControllerWithIdentifier:@"myVC"];
[self.navigationController pushViewController:secondClass animated:YES];
}
-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
//Here assign yellow background color to first row and white color to the second row
}
在我的单元格中,我添加了 prepareForReuse 但这不起作用...
- (void)prepareForReuse {
[super prepareForReuse];
[self removeFromSuperview];
[self setNeedsLayout];
}
【问题讨论】:
-
这段代码可能还不足以找到问题所在。请添加collection view的dataSource和delegate方法。
-
didSelectItemAtIndexPath仅在用户选择项目时调用。滚动不会调用那个方法 -
我正在添加我的代码,我不想在滚动时调用 didSelect。我的问题是重用和重新绘制单元格,因为我的第一个单元格失去了添加的功能。我认为正在写其他索引,当我点击 0 位置时确实是 1 个单元格索引
-
@user3745888 我相信theMachSystem 的答案实际上可能是您正在寻找的解决方案。单元的可重用性可能会导致您遇到的问题
标签: ios objective-c uicollectionview uicollectionviewcell prepareforreuse