解析UITableViewCell的reuse问题

来源:互联网 发布:java的api文档在哪里 编辑:程序博客网 时间:2024/05/23 02:03

http://blog.csdn.net/xunyn/article/details/8316358


UITableView在iOS开发中会经常使用,对于行数很多的UITableView,可以通过UITableViewCell的重用,来保证执行效率。源码下载点击这里。

我们通过代码来探索UITableViewCell重用的实现,下面是一段使用UITableView的代码,

[cpp] view plaincopyprint?
  1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
  2. {  
  3.      static NSString *CellIdentifier = @"myCell";  
  4.     //NSString *CellIdentifier = [NSString stringWithFormat:@"myCell_%d",indexPath.row];  
  5.   
  6.     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];  
  7.       
  8.     if (cell == nil) {  
  9.           
  10.         cell = [[UITableViewCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:@"myCell"];  
  11.         UITextField *tf;  
  12.         tf = [[UITextField alloc] initWithFrame:CGRectMake(100, 10, 150, 40) ];  
  13.         tf.delegate = self;  
  14.         tf.borderStyle = UITextBorderStyleRoundedRect;  
  15.         [cell  addSubview:tf];  
  16.         [tf release];  
  17.           
  18.           
  19.     }  
  20.     // Configure the cell...  
  21.     cell.textLabel.text = [NSString stringWithFormat:@"%d",indexPath.row];  
  22.       
  23.     return cell;  
  24. }  

运行结果是这样


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


我们回到dequeueReusableCellWithIdentifier的定义

[cpp] view plaincopyprint?
  1. - (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 plaincopyprint?
  1. // Configure the cell...  
  2. cell.textLabel.text = [NSString stringWithFormat:@"%d",indexPath.row];  

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

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

[cpp] view plaincopyprint?
  1. NSString *CellIdentifier = [NSString stringWithFormat:@"myCell_%d",indexPath.row];  
对于每一行,设定不同的reuseIdentifier。
原创粉丝点击