gpt4 book ai didi

ios - UICollectionViewCell 滚动时重叠

转载 作者:行者123 更新时间:2023-12-01 17:53:00 44 4
gpt4 key购买 nike

以下代码是一个非常简单的程序,用于在 UICollectionView 中显示 1-10000 之间的数字。 .它在不滚动的情况下正确显示,但是如果您向下滚动并向后滚动 Collection View ,则单元格会重叠。

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 10000;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(100,30);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
NSString *identifier = @"cell_id";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[label setText:[NSString stringWithFormat:@"%d", indexPath.item, nil]];
[cell.contentView addSubview:label];

return cell;
}

最佳答案

这里的问题是标签被反复添加到 View 的单元格中。重复使用单元格时不会删除旧标签,因此您会看到多个数字重叠。解决方案可以是像这样删除旧标签

for (UIView *view in cell.contentView.subviews) {
if ([view isKindOfClass:[UILabel class]]) {
[view removeFromSuperview];
}
}

在添加到单元格之前。但是,当 subview 数量增加时,这会产生性能问题。您可以创建带有标签的自定义单元格,然后更新其值。我没有尝试过,但我相信它会起作用。希望这可以帮助

关于ios - UICollectionViewCell 滚动时重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23647833/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com