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

解析UITableViewCell的重用

2016-02-22 22:24 393 查看
UITableView在iOS开发中会经常使用,对于行数很多的UITableView,可以通过UITableViewCell的重用,来保证执行效率。
我们通过代码来探索UITableViewCell重用的实现,下面是一段使用UITableView的代码,

[cpp] view
plain copy

print?

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

{

static NSString *CellIdentifier = @"myCell";

//NSString *CellIdentifier = [NSString stringWithFormat:@"myCell_%d",indexPath.row];

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:@"myCell"];

UITextField *tf;

tf = [[UITextField alloc] initWithFrame:CGRectMake(100, 10, 150, 40) ];

tf.delegate = self;

tf.borderStyle = UITextBorderStyleRoundedRect;

[cell addSubview:tf];

[tf release];

}

// Configure the cell...

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

return cell;

}

运行结果是这样



我们在textfield里输入label的序号,然而我们上下拖动后,结果是textfield的值并没有得到保存,其随着cell的重用而变化。

我们回到dequeueReusableCellWithIdentifier的定义

[cpp] view
plain copy

print?

- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier; // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.

使用委托来获取一个已经分配的cell,代替分配新的一个;在这个例子中,将当前屏幕下创建的Cell都先加入到对象池,这是对象池的內Cell的个数大致是8,当我们滑动TableView时,将使用dequeueReusableCellWithIdentifier方法返回对象,该方法通过

reuseIdentifier(“myCell”)在对象池中,查找之前已经放入的cell对象。

然后从对象池中,取出之前放入的,然后执行

[cpp] view
plain copy

print?

// Configure the cell...

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

所以我们需要为textfield里的text内容设置model层,然后配置textfield的内容,像我们对textLabel的设置一样

还有了不完美的解决方案,既然它重用出问题,就不让它重用,代码如下

[cpp] view
plain copy

print?

NSString *CellIdentifier = [NSString stringWithFormat:@"myCell_%d",indexPath.row];

对于每一行,设定不同的reuseIdentifier。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: