

1,声明和创建要用的TableView,遵循数据源方法和代理,来用于实现数据加载和点击事件的接收.
1,声明控件
@interface TestViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (strong, nonatomic) UITableView *tableView;
@end
2,添加到self.view
2.1直接创建添加
self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 10, ScreenWidth, ScreenHeight - SafeAreaTopHeight - SafeBottomHeight - 56) style:UITableViewStylePlain];
self.tableView.backgroundColor = [UIColor clearColor];
self.tableView.separatorColor = Theme_Line_Color;
self.tableView.delegate =self;
self.tableView.dataSource = self;
// 根据ID 这个标识 注册对应的cell类型 为UITableViewCell(只注册一次)
//纯代码写的cell的注册方式
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ID"];
//如果你是用xib创建的cell的注册方式
UINib *nib = [UINib nibWithNibName:NSStringFromClass([testCell class]) bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier:@"ID"];
[self.view addSubview:self.tableView];
2.2,懒加载的方式
[self.view addSubview:self.tableView];
- (UITableView *)tableView {
if (!_tableView) {
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 10, ScreenWidth, ScreenHeight - SafeAreaTopHeight - SafeBottomHeight - 56) style:UITableViewStylePlain];
_tableView.backgroundColor = [UIColor clearColor];
_tableView.separatorColor = Theme_Line_Color;
_tableView.delegate =self;
_tableView.dataSource = self;
//纯代码写的cell的注册方式
// [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ID"];
UINib *nib = [UINib nibWithNibName:NSStringFromClass([CollectionWebInformationCell class]) bundle:nil];
[_tableView registerNib:nib forCellReuseIdentifier:CollectionWebInformationCellID];
}
return _tableView;
}
3,数据的加载
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;//一共多少组,默认为1,不是必须实现的,可以不写这个方法
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 4;//每一组里面有多少个cell
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 127;//设置每个cell的高度
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//3.0 先确定cell的重用标识:命名规范:数据的模型+ID
static NSString *ID = @"carID"; static修饰局部变量,局部变量只会分配一次内存地址
//3.1 查看缓存池中是否有带重用标识的cell缓存池方法中封装了,如果缓存池中没有,就根据注册创建新的cell,然后返回给我们一个带ID的cell后面还封装了一层,如果也没有注册呢,会根据storyboard中是否标记了在重用cell,来创建一个新的cell然后返回
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//取消cell点击效果
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// 3.3 覆盖cell上的数据
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
网友评论