面试题答案
一键面试- 注册自定义单元格类:
- 首先创建一个自定义的
UITableViewCell
子类,假设名为CustomTableViewCell
。 - 在视图控制器的
viewDidLoad
方法中注册这个自定义单元格类。
- (void)viewDidLoad { [super viewDidLoad]; // 注册自定义单元格类 [self.tableView registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"CustomCellIdentifier"]; }
- 首先创建一个自定义的
- 在
cellForRowAtIndexPath:
方法中配置单元格:- 从复用队列中取出单元格或创建新的单元格。
- 配置单元格的内容,比如设置文本、图片等。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCellIdentifier" forIndexPath:indexPath]; // 配置单元格内容,例如 cell.textLabel.text = @"示例文本"; cell.imageView.image = [UIImage imageNamed:@"exampleImage"]; return cell; }
- 自定义单元格类
CustomTableViewCell
的实现:- 可以在自定义单元格类中添加自定义的属性和方法,用于更好地定制单元格样式。
// CustomTableViewCell.h #import <UIKit/UIKit.h> @interface CustomTableViewCell : UITableViewCell @property (nonatomic, strong) UILabel *customLabel; @property (nonatomic, strong) UIImageView *customImageView; - (void)configureCellWithData:(id)data; @end // CustomTableViewCell.m #import "CustomTableViewCell.h" @implementation CustomTableViewCell - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { _customLabel = [[UILabel alloc] init]; [self.contentView addSubview:_customLabel]; _customImageView = [[UIImageView alloc] init]; [self.contentView addSubview:_customImageView]; // 布局相关代码省略 } return self; } - (void)configureCellWithData:(id)data { // 根据数据配置单元格,例如 if ([data isKindOfClass:[NSString class]]) { self.customLabel.text = data; } } @end
- 在
cellForRowAtIndexPath:
方法中可以这样使用:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCellIdentifier" forIndexPath:indexPath]; [cell configureCellWithData:@"示例数据"]; return cell; }