开发过程中,cell的复用是一直关心的技术点,在cell的使用过程中展现复杂的UI界面一般都是自定义cell,而cell的使用过程中,就会有的倾向于纯代码,或者XIB,而我就是XIB的死党。所以复用cell的方式就会有两种方式,纯代码,XIB
//第一中cell的复用标识
static NSString* firseCellid = @"codeFirstCell";
纯代码:
有三种方式:1.直接在使用前regis:
[self.tableView registerClass:[SEFirstCell class] forCellReuseIdentifier:firseCellid];
然后在cell的返回代理方法里面直接使用:
//2.在数据源方法中,直接“dequeueReusableCellWithIdentifier”,获取到复用的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
SEFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:firseCellid];
cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
NSLog(@"%@",cell);
return cell;
}
2.在自定义的cell的.h文件中写一个初始化借口;
+(instancetype)CellWithTableView:(UITableView *)tableView;
然后在.m文件中实现:
+ (instancetype)CellWithTableView:(UITableView *)tableView{
ZHZTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:firseCellid];
if (!cell) {
cell = [[ZHZTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:firseCellid];
}
return cell;
}
在人后就是直接在cell的代理方法直接用了。
//在控制器中,调用cell的时候,直接使用类方法就好,非常的方便
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
ZHZTableViewCell *cell = [ZHZTableViewCell secCellWithTableView:tableView];
cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
return cell;
}
3. 简单方便不用写接口:
直接在cell的返回代理方法里面写。
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
ZHZTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:firseCellid];
if (!cell) {
cell = [[ZHZTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:firseCellid];
}
return cell;
}
二.XIB方式,也有两种:
1.类似于出代码的第一种方法:在使用之前注册:只是这次注册的是XIB
[self.table registerNib:[UINib nibWithNibName:@"ZHZTableViewCell" bundle:nil] forCellReuseIdentifier:threeCellid];
然后就在代理方法中使用就可以了:
//2.在数据源方法中,直接“dequeueReusableCellWithIdentifier”,获取到复用的cell(和方法一相同)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
ZHZTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:firseCellid];
cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
NSLog(@"%@",cell);
return cell;
}
2.类似纯代码方式二在头文件里面写接口然后在实现文件里面实现接口,只是这次实现的方式 是以XIB的方式实现的。
//2.将这个方法重写一下,加载和注册nib
+ (instancetype)CellWithTableView:(UITableView *)tableView{
UINib *nib = [UINib nibWithNibName:@"ZHZTableViewCell" bundle:nil];
[tableView registerNib:nib forCellReuseIdentifier:firseCellid];
ZHZTableViewCell *fourCell = [[nib instantiateWithOwner: nib options:nil] lastObject];
return fourCell;
}
然后在cell的代理方法里面实现。
3.第三种类比,好蛋疼的重复,
大概六种的cell的注册方法,官方是推荐出代码的第二种和XIB的第二种方式的至于其他两种方式的效率或者性能有待考究。。。