OGeek|极客世界-中国程序员成长平台

标题: ios - TableView滚动时如何避免UITableViewCell重复添加自定义标签? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:38
标题: ios - TableView滚动时如何避免UITableViewCell重复添加自定义标签?

我创建了一个自定义单元:

#import <UIKit/UIKit.h>
#import "RecruitmentResumeEntity.h"

@interface RecruimentListItemCell : UITableViewCell
@property (nonatomic, strong) RecruitmentResumeEntity *entity;
@end

在 .m 文件中设置实体方法时,我添加了三个标签:

-(void)setEntityRecruitmentResumeEntity *)entity {

   _entity = entity;

   float labelHeight = 17;

   CGRect frame = CGRectMake(64, 45, 0, labelHeight);
   UILabel *cityLabel = [self createTagLabelWithFrame:frame text:_entity.city backgroundColor"#e5986f"];
   [self.contentView addSubview:cityLabel];

   UILabel *workExperienceLabel = [self createTagLabelWithFrame:CGRectMake(cityLabel.x+cityLabel.width +10, cityLabel.y, 0, labelHeight) text:[NSString stringWithFormat"%@年",_entity.workExperience] backgroundColor"#81A0D7"];
   [self.contentView addSubview:workExperienceLabel];

   UILabel *expectSalaryLabel = [self createTagLabelWithFrame:CGRectMake(workExperienceLabel.x+workExperienceLabel.width +10, workExperienceLabel.y, 0, labelHeight) text:_entity.expectSalary backgroundColor"#94C373"];
   [self.contentView addSubview:expectSalaryLabel];
}

在 Controller cellForRowAtIndexPath 方法中获取自定义单元格并设置实体。但是当我运行应用程序,滚动 UITableView 时,我发现单元格重复创建了三个标签,我只希望每个单元格只有三个标签。我是不是弄错了什么或遗漏了什么。谁能帮助我?等待你的帮助。谢谢。 enter image description here

- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath {

   RecruitmentResumeEntity *entity = _dataList[indexPath.row];
   RecruimentListItemCell *cell = [tableView dequeueReusableCellWithIdentifier"RecruimentListItemCell" forIndexPath:indexPath];
   cell.entity = entity;

   return cell;
}



Best Answer-推荐答案


这似乎是您没有正确重新使用单元格的问题。

当你调用 RecruimentListItemCell *cell = [tableView dequeueReusableCellWithIdentifier"RecruimentListItemCell"forIndexPath:indexPath]; 系统会给你一个它认为可以重复使用的单元格来显示下一个信息需要显示的单元格,但在重复使用之前正确准备此单元格是您的责任。

为此,您必须在 RecruimentListItemCell 中实现 -(void)prepareForReuse,在那里您必须确保所有需要重新填充的项目正确重置单元格,以便可以正确重新填充单元格。

例如,如果在 RecruimentListItemCell 中添加标签“SampleLable”作为 subview ,但在 -( void)prepareForReuse 然后每次重用单元格时,“SampleLable”都会一次又一次地添加到其中,最终你会注意到事情看起来不像他们应该的那样,就像你的“重复创建标签”一样

这就是 prepareForReuse 在我的一个应用中的样子:

-(void)prepareForReuse {

[super prepareForReuse];

[_statesView.activityIcon1 setHidden:YES];
[_statesView.activityIcon2 setHidden:YES];

_title.text = nil;
_infoText.text = nil;
_createdTime.text = nil;
_cellType = CustomCellTypeNone;

[_progressView setProgress:0];
}

在这里你可以看到我刚刚设置为 nil 的一些项目(并不总是最好的方法),如果需要,这些项目只是重新放入。你可以看到我隐藏了activityIcon 1和2。 当下一个单元格出现时,如果它需要图标,它会简单地取消隐藏它们,如果它需要标签,那么它会添加它们。

因此,如果我不将所有标签都归零,那么它们会留在 View 中,并且下一个单元格可能会添加自己的标签,这将导致您遇到的问题。

关于ios - TableView滚动时如何避免UITableViewCell重复添加自定义标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34781239/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4