滚动UICollectionView时,为什么我的单元格子视图帧会发生变化

时间:2014-04-12 13:33:01

标签: ios objective-c uicollectionview uicollectionviewcell

基本上,我有一个UICollectionViewCell,它从数据源加载值,另外它应该将子视图帧的高度设置为等于数据源中的一个值。

我遇到的问题是,当我第一次运行项目时它看起来是正确的,但当我来回滚动几次时,由于单元格被重用,文本值保持不变但子视图的框架发生了变化

令我困惑的是,在单元格中的标签中设置文本的变量与在同一单元格中设置子视图的高度值的变量相同;但是标签文本总是正确的,但UIView框架的高度会随着滚动而不断变化。

我知道这可能与细胞如何被重复使用有关,但我不能把手指放在它上面。

下面是我的cellForRowAtIndexPath代码。谢谢!

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{

DailyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DayCell" forIndexPath:indexPath];

cell.backgroundContainerView.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.3f];

float total = [[dummyData objectAtIndex:indexPath.row][@"total"] floatValue] * 2;

UIView * backgroundFillView = [UIView new];
if (![cell viewWithTag:1000]) {
    NSLog(@"Creating backgroundFillView on Cell: %ld", (long)indexPath.row);

    backgroundFillView.tag = 1000;
    [cell.backgroundContainerView addSubview:backgroundFillView];

}


cell.debugCellNumber.text = [NSString stringWithFormat:@"%ld", (long)indexPath.row];
cell.debugCellTotal.text = [NSString stringWithFormat:@"%f", total];

backgroundFillView.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.5f];
backgroundFillView.frame = CGRectMake(0, 200 - total, 60, total);

NSLog(@"Cell: %ld, total: %f", (long)indexPath.row, total);
NSLog(@"Cell: %ld, backgroundFillView Height: %f", indexPath.row, backgroundFillView.frame.size.height);
NSLog(@"Cell: %ld, backgroundFillView Y: %f", indexPath.row, backgroundFillView.frame.origin.y);

return cell;
}

1 个答案:

答案 0 :(得分:1)

首次填充单元格时,只需添加backgroundFillView。不是在重新使用时。

替换:

UIView * backgroundFillView = [UIView new];
if (![cell viewWithTag:1000]) {
    NSLog(@"Creating backgroundFillView on Cell: %ld", (long)indexPath.row);

    backgroundFillView.tag = 1000;
    [cell.backgroundContainerView addSubview:backgroundFillView];

}

使用:

UIView * backgroundFillView = [cell viewWithTag:1000];
if (! backgroundFillView) {
    NSLog(@"Creating backgroundFillView on Cell: %ld", (long)indexPath.row);
    backgroundFillView = [UIView new];

    backgroundFillView.tag = 1000;
    [cell.backgroundContainerView addSubview:backgroundFillView];

}