初始化
self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0,kWidth,kHeight) style:UITableViewStylePlain];
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.view addSubview:self.tableView];
//[self.tableView registerClass:[ZJTableViewCell class] forCellReuseIdentifier:@"cell"];
代理和数据源
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 40;
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"cell";
ZJTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if(!cell){
cell = [[ZJTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
cell.student = self.array[indexPath.row];
}
return cell;
}
ZJTableViewCell.h
#import <UIKit/UIKit.h>
@class Student;
NS_ASSUME_NONNULL_BEGIN
@interface ZJTableViewCell : UITableViewCell
@property(nonatomic,strong)Student *student;
@end
NS_ASSUME_NONNULL_END
ZJTableViewCell.m
#import "ZJTableViewCell.h"
#import "Student.h"
@interface ZJTableViewCell()
@property(nonatomic,strong)UILabel *desLbl;
@end
@implementation ZJTableViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
if(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]){
//初始化并添加子控件(设置字体、文字颜色等)
self.desLbl = [[UILabel alloc]init];
[self.contentView addSubview:self.desLbl];
}
return self;
}
- (void)layoutSubviews{
[super layoutSubviews];
//计算和设置所有子控件的frame
self.desLbl.frame = CGRectMake(100,10,100,20);
}
- (void)setStudent:(Student *)student{
self.student = student;
self.desLbl.text = self.student.name;
}
@end