(转)UITableViewCell复用问题
生活随笔
收集整理的這篇文章主要介紹了
(转)UITableViewCell复用问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
列舉兩個場景對比一下,也許tableviewcell的復用就很清晰明了了。
1, 1 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 2 3 static NSString *CellIdentifier = @"cell1"; 4 UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 5 6 if (cell == nil) { 7 8 cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 9 10 UILabel *labelTest = [[UILabel alloc]init]; 11 12 [labelTest setFrame:CGRectMake(2, 2, 80, 40)]; 13 14 [labelTest setBackgroundColor:[UIColor clearColor]]; 15 16 [labelTest setTag:1]; 17 18 [[cell contentView]addSubview:labelTest]; 19 20 } 21 22 UILabel *label1 = (UILabel*)[cell viewWithTag:1]; 23 24 [label1 setText:[self.tests objectAtIndex:indexPath.row]]; 25 26 return cell; 27 28 } 2, 1 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{ 2 3 static NSString *CellIdentifier = @"cell1"; 4 UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 5 6 if (cell == nil) { 7 8 cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 9 10 } 11 12 UILabel *labelTest = [[UILabel alloc]init]; 13 14 [labelTest setFrame:CGRectMake(2, 2, 80, 40)]; 15 16 [labelTest setBackgroundColor:[UIColor clearColor]]; //之所以這里背景設為透明,就是為了后面讓大家看到cell上疊加的label。 17 18 [labelTest setTag:1]; 19 20 [[cell contentView]addSubview:labelTest]; 21 22 [labelTest setText:[self.tests objectAtIndex:indexPath.row]]; 23 24 return cell; 25 } 當你上下來回滑動tableview的時候就會看到區別,第一種程序界面不會出現異常,但是第二種就不是了,會出現字體疊加現象,其實更確切的是多個label的疊加。為什么呢,因為在tableview刷新的時候,如果那個位置已經有現成的cell,它就不會再重新請求資源生成新的cell了,而是復用原來的cell。所以對于對于第一種,代碼的思路是第一次在cell不存在的時候生成cell,定義cell樣式,以后不管是刷新還是重新請求還好,它都只是復用已生成的cell。而第二種思路是,在cell不存在的時候,請求生成cell,然后給cell上添加label,刷新的時候,會復用已有的cell,但是會重復添加label,故造成重疊的現象。 之前類似的問題來回困擾了我好多次,我都沒有下決心徹底搞清楚,每次都是得過且過,只要程序最好調好了,就OK。今天又碰到了類似的問題,終于大致搞清楚了,希望以后不會再被它坑害。 備注:原文地址:http://my.oschina.net/u/1378445/blog/186187轉載于:https://www.cnblogs.com/fanyufan/p/3587436.html
總結
以上是生活随笔為你收集整理的(转)UITableViewCell复用问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多人协作代码--公共库的引用与业务约定
- 下一篇: 记录所遇到的编译错误及解决方法