您的位置:首页 > 产品设计 > UI/UE

UITableView 加载cell 的几种常用方式

2016-11-08 21:49 651 查看
开发的过程中,由于经常用到tableview,加载cell,也经常忘记所有,记录下经常用的几种方式

1 代码加载cell

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *idfity=[NSString stringWithFormat:@"%ld%ld",(long)indexPath.section,(long)indexPath.row];
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:idfity];
if (!cell) {
cell=[[UITableViewCell alloc]initWithStyle:0 reuseIdentifier:idfity];

}
return cell;
}


这种经常用的方式,也是最早开始用的方式,加载比较麻烦,代码量比较多;

2 tableview registerClass 的方式加载

首先在viewdidload 方法注册cell

[tableView registerClass:[TableViewCell class] forCellReuseIdentifier:IDENTIFIER];


然后

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:IDENTIFIER];
//这里会发现,cell一直都不是nil,不再需要创建
if (cell == nil) {
}
return cell;
}


这样创建cell的方式,cell 不会为空,所有也不需要判断cell==nil 的代码了,

3 通过xib 文件加载cell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell* cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:IDENTIFIER];
if (cell == nil) {
cell = [[NSBundle mainBundle]loadNibNamed:@"TableViewCell" owner:nil options:nil].firstObject;
}

return cell;
}


这样加载和第一种代码加载的结果一样,cell 开始是空的,一屏幕划过去后,cell 就不会加载后,不会为空,开始重用,

4 用注册的方式加载xib 文件

[tableView registerNib:[UINib nibWithNibName:@"TableViewCell" bundle:nil] forCellReuseIdentifier:IDENTIFIER];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell* cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:IDENTIFIER];
if (cell == nil) {
//cell一直都不是nil,不再需要创建,所有也不需要判断为空了
}
return cell;
}


这种和第第二种代码注册结果是一样的,

5 通过storyboard 创建的tableview cell 加载方式

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
XXXTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"XXXTableViewCell"];
[cell updateView:receiver];
return cell;
}


sb 创建更简单化了cell 的加载方式

以上就是cell 加载的几种方式,又不对的地方还望指正,谢谢
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: