gpt4 book ai didi

ios - collectionView 可重用单元格导致错误

转载 作者:行者123 更新时间:2023-12-01 18:11:38 27 4
gpt4 key购买 nike

我正在创建一个collectionView,其单元格大小不同且内容不同。我正在为这些单元格使用单元格原型(prototype),但是,当我添加多个单元格时,我会遇到奇怪的 UI 错误:

这就是它应该看起来的样子
Supposed to
这就是它的实际样子
Fail

代码:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
Card *card = [[[usermanager getSelectedUser] getCards] objectAtIndex:indexPath.item];

[card setupLayout];

UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
if(cell == nil){
cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cardCell" forIndexPath:indexPath];
}
[cell addSubview:card];
cell.clipsToBounds = YES;
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;

cell.layer.shadowPath = [[UIBezierPath bezierPathWithRect:cell.bounds] CGPath];

//Add dropshadow
cell.contentView.layer.borderWidth = 1.0f;
cell.contentView.layer.borderColor = [UIColor clearColor].CGColor;
cell.contentView.layer.masksToBounds = YES;

cell.layer.shadowColor = [UIColor blackColor].CGColor;
cell.layer.shadowOffset = CGSizeMake(0, 5.0f);
cell.layer.shadowRadius = 2.0f;
cell.layer.shadowOpacity = 0.5f;
cell.layer.masksToBounds = NO;

cell.layer.borderColor = [UIColor yellowColor].CGColor;
cell.layer.borderWidth = 2.0f;

return cell;
}

这可能与我使用可重复使用的单元格有关。因为当我在 Storyboard中为这些单元创建 2 个不同的原型(prototype)时,它们完全没有问题。谁能帮我?谢谢

最佳答案

正如您所说:您的单元格将被重复使用,因此如果您更改任何布局或框架或颜色,这些属性将与您在下次使用单元格时设置的一样。您应该继承 UICollectionViewCell 并实现方法 prepareForReuse ,您必须将单元格的所有 View 和属性重置为原始值,并且您必须删除 subview 卡:

-(void)prepareForReuse {
[super prepareForReuse];
// Reset all, for example backgroundView
self.backgroundView = nil;
}

还有一点:你为什么调用 UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];那是不正确的。您只需要 UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cardCell" forIndexPath:indexPath];

关于ios - collectionView 可重用单元格导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29984483/

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