如何在Objective-C自定义TableViewCell中正确通过代码添加图片
问题解决方法
核心问题分析
- 每次
cellForRowAtIndexPath中创建新的UIImageView并添加到cell,会导致cell复用时重复添加视图,出现显示混乱 UITableViewCell没有viewDidLoad生命周期方法,所以你在自定义cell中写的viewDidLoad永远不会触发,xib创建的cell应该用awakeFromNib方法初始化视图
修正后的自定义cell代码
@implementation customCellSingersAlbumVC - (void)awakeFromNib { [super awakeFromNib]; // 创建图标视图,只初始化一次,避免复用重复添加 UIImageView *iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(16, 12, 24, 24)]; // 按通知图标尺寸设置布局 iconImageView.tag = 1001; [self.contentView addSubview:iconImageView]; } @end
修正后的ViewController代码
@implementation albumsSingerVC - (void)viewDidLoad{ [super viewDidLoad]; _matableview.delegate = self; _matableview.dataSource = self; // 提前注册xib,不要在cellForRow里重复注册 [_matableview registerNib:[UINib nibWithNibName:@"customCellSingersAlbumView" bundle:nil] forCellReuseIdentifier:@"customCell"]; } - (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath { static NSString *MyIdentifier = @"customCell"; customCellSingersAlbumVC *cell = (customCellSingersAlbumVC*)[tableView dequeueReusableCellWithIdentifier:MyIdentifier forIndexPath:indexPath]; // 通过tag获取已创建的图标视图,设置图片 UIImageView *iconImageView = (UIImageView*)[cell.contentView viewWithTag:1001]; iconImageView.image = [UIImage imageNamed:@"pink.png"]; return cell; } @end
额外优化建议
- 给自定义cell添加专属属性替代tag查找,代码更严谨:
在customCellSingersAlbumVC.h中声明:
在@property (nonatomic, strong) UIImageView *iconImageView;awakeFromNib中初始化:
在self.iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(16, 12, 24, 24)]; [self.contentView addSubview:self.iconImageView];cellForRow中直接使用:cell.iconImageView.image = [UIImage imageNamed:@"pink.png"]; - 改用AutoLayout替代frame布局,适配不同屏幕尺寸:
给iconImageView添加约束(比如左间距16pt、上下居中、宽高24pt),布局更灵活稳定。
内容的提问来源于stack exchange,提问作者Six
相关产品推荐
相关产品推荐

