您的位置:首页 > 其它

创建cell的几种方式

2016-03-28 00:45 381 查看
方式一 注册cell -> 无需为cell绑定标识符 [使用UIViewController完成!]

l 1> static NSString * const ID = @"cell"; // 全局ID变量

l 2> 在视图加载完成后使用tableView进行注册cell

- (void)viewDidLoad {

[super viewDidLoad];

[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];

}

l 3> 在数据源方法cellForRowAtIndexPath:中直接从缓存池中取cell即可!

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

// 如果是注册cell.那么下面从tableView缓存池中取cell两种的方式方式都可用!

// 获取cell 方式一

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

// 获取cell 方式二

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];

cell.textLabel.text = [NSString stringWithFormat:@"cell - %zd",indexPath.row];

return cell;

}

方式二 为cell绑定标识符 -> storyboard中进行设置

l 1> 在storyboard中为cell绑定标识符

l 2> 在数据源方法cellForRowAtIndexPath:中直接从缓存池中取cell即可!

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

// 无需判断,直接获取即可!

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

cell.textLabel.text = [NSString stringWithFormat:@"cell - %zd",indexPath.row];

return cell;

}

方式三 在数据源方法cellForRowAtIndexPath:中直接设置!

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *ID = @"cell";

// 如果是创建局部变量的ID.那么下面这种从缓存池中取cell的方式会使程序崩溃! // 程序崩溃代码! 错误!

// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];

// 程序正确!

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];

}

cell.textLabel.text = [NSString stringWithFormat:@"cell - %zd",indexPath.row];

return cell;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: