在我们使用UITableView时,常常会遇到系统提供的样式无法满足项目需求的时候,这时需要我们根据需求自定义cell
注册与非注册
注册
注册主要是在获取复用的cell时,如果没有可复用的cell,系统将会自动的使用注册时提供的类来创建可用的cell,这样确保了返回的一定是可用的cell。
[_tableView registerClass:[MessageCell class] forCellReuseIdentifier:@"cell"];
MessageCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
非注册
非注册时就需要判断返回的cell是否为空,如果为空,则为它创建一个新的cell。
UITableViewCell* cell = [_tableView dequeueReusableCellWithIdentifier:@"cell"];
if(cell == nil) {
cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
}
代码自定义cell:
新建一个继承自UITableViewCell的类,为该类添加我们需要的属性
@interface MessageCell : UITableViewCell
// 基本数据
@property (nonatomic, weak) UILabel* userName;
@property (nonatomic, weak) UILabel* message;
@end
重写- (instancetype) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier方法
添加我们需要显示的子控件为子控件某些不变的属性(如字体)进行设置
- (instancetype) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
UILabel* userName = [[UILabel alloc] init];
userName.font = nameFont;
[self.contentView addSubview:userName];
self.userName = userName;
UILabel* message = [[UILabel alloc] init];
message.font = messageFont;
[self.contentView addSubview:message];
self.message = message;
}
return self;
}
实现TableView的数据源方法返回我们自定义的cell
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString* cellStr = @"cell";
MessageCell* cell = [_tableView dequeueReusableCellWithIdentifier:cellStr];
if (cell == nil) {
cell = [[MessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellStr];
}
/* 传递数据给cell */
return cell;
}
文章来源
发表评论