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

UITableView使用简介

2014-04-08 14:44 302 查看
UITableView是个使用很广的控件,在使用一段时间之后,有了些理解,在此做一些记录。

一、初始化

先看一段代码。

UITableView *mTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] bounds] style:UITableViewStylePlain];
[mTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:identifier]; // 注册一个类以供创建table cells使用
mTableView.delegate = self;
mTableView.dataSource = self;
代码的第二行是ios6.0以后的东西,注册一个UITableViewCell类,是配合接下来这段代码使用的。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}

cell.textLabel.text = @"表格测试";

return cell;
}


准确来说,是配合这一句代码使用的。
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

[tableView dequeueReusableCellWithIdentifier:identifier]的返回值是id,
如果tableview里面有能够reuse的cell,则返回一个cell,这就ok了。
如果tableview里面没有能够reuse的,那么就返回一个nil。这样cell就是一个nil,因此,我们得做一个判断,如果cell为空,利用这一句代码

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


初始化一个。当然,这是在之前我没有注册过cell的情况下。
好了。现在我一开始注册了一个cell,那么如果tableview里面有能够reuse的cell,则返回一个cell,这跟之前一样。
但是如果tableview里面没有能够reuse的,那么就会调用initWithStyle: reuseIdentifier: 这个方法,自动给我生成一个cell。
说白了,如果之前注册了的话,就能把if那个判断给省了。至于这种方法有没有复用cell,这就不太清楚了,按道理是复用了。以后有时间再了解。我觉得还是先用原来的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  UITableView