在UICollectionView中更新不可见的单元格

时间:2015-06-24 11:13:06

标签: ios uicollectionview uicollectionviewcell expand nsindexpath

我的应用程序中需要一个可扩展的UICollectionView - 所以我遇到了这个项目(https://github.com/apploft/APLExpandableCollectionView)。它是UICollectionView的子类,用于实现展开和折叠行为。

我已将演示应用扩展为在可扩展单元格中显示+或 - 按钮。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
APLCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"APLCollectionViewCell" forIndexPath:indexPath];

if (indexPath.item == 0) {
    cell.label.text = [NSString stringWithFormat:@"Section %li", (long)indexPath.section + 1];
    cell.backgroundColor = [UIColor colorWithRed:58./255. green:165./255. blue:192./255. alpha:1.];
    cell.indentView.hidden = YES;
    cell.label_OnOff.text = @"+";
} else {
    cell.label.text = [NSString stringWithFormat:@"Item %li", (long)indexPath.row];
    cell.backgroundColor = [UIColor colorWithRed:58./255. green:165./255. blue:192./255. alpha:.5];
    cell.indentView.hidden = NO;
    [cell.label_OnOff setHidden:YES];
}

return cell; 
}

要在+和 - 之间切换,我实现了委托方法:

- (void)collectionView:(UICollectionView *)collectionView didCollapseItemAtIndexPath:(NSIndexPath *)indexPath
{
    APLCollectionViewCell *cell = (APLCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    cell.label_OnOff.text = @"+";
}

- (void)collectionView:(UICollectionView *)collectionView didExpandItemAtIndexPath:(NSIndexPath *)indexPath
{
    APLCollectionViewCell *cell = (APLCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    cell.label_OnOff.text = @"-";
}

正如您在屏幕截图中看到的,可见单元格已正确更新。一旦我向下滚动到以前看不见的单元格,+按钮就会消失。 当UICollectionView中只有少数项目时,不会发生此问题,因此无需滚动到其他项目。

Screenshot

我是否为隐形单元格的IndexPath做错了什么,或者您对我有任何其他提示吗? 谢谢!

2 个答案:

答案 0 :(得分:3)

添加以下行

cell.indentView.hidden = NO;

在cellForItemAtIndexPath中的if else条件之前。它可能对你有所帮助。

答案 1 :(得分:0)

Thx Bhanu,

你的回答指出了正确的方向。集合视图中的单元格已重新使用,因此在检查IndexPath时,我必须设置cell.label_OnOff.hidden = NO;cell.label_OnOff.hidden = YES;

相关问题