关于表格视图UITableView的流畅度优化小结

UITableView的优化小结

UITableView在ios的实际开发中使用频次有多重不用多说,而它的优化技巧既是难点也是必须掌握的要点;作为一个在UITableView的优化路上还没走多远的初学者,最近在网上到处找了蛮多相关资料来阅读,自己也结合自己的项目做了一些思索和实践,让我们一起来学习吧!如果你在这方面已经有了一些心得,郑重推荐一个开源项目VVeboTableViewDemo,值得学习!

UITableView的核心简介

  • UITableView的核心思想就是对UITableViewCell的重用,大概原理就是:UITableView刚开始只会创建一个屏幕或者一个屏幕多一点的UITableViewCell,当UITableView滑动的时候,滑出屏幕的UITableViewCell会被放到重用池中等待重用,而由于滑动将在屏幕上出现新的UITableViewCell,这些UITableViewCell首先是去重用池中取,取不到再去创建新的;这样做的好处就是,你的UITableView从始至终都只会创建一个屏幕的UITableViewCell,而不会由于你的tableview有几百行cell就去创建几百个cell。
  • 要对UITableView进行优化,主要的代码将放在以下两个UITableView的代理方法中:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

那么在实际开发中,在我们创建好UITableView后,首先多次调用heightForRowAtIndexPath的方法从而确定UITableView的contentSize和cell的位置,然后调用cellForRowAtIndexPath创建cell,并显示在屏幕上;优化的部分就集中在以上两个方法中。

1.0 原始代码
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BTNewsFlashCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NEWSCELL" forIndexPath:indexPath];
    BTNewsFlashModel *model = _dataArray[indexPath.row];
    cell.model = model;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BTNewsFlashModel *model = _dataArray[indexPath.row];
    NSInteger height = model.APicHeight;
    return height*WIDTH/model.APicWidth;
}

在这段代码中第一个方法起到为cell赋值(model)的作用,第二个方法起到根据数据源动态计算行高的方法。问题就处在第二个方法中,如果我们要创建100个cell甚至更多,就会去计算100次,而且每当你滚动cell的时候还会去计算,这就很耗费资源,甚至如果你的cell排布很复杂,那计算量就很可怕了。。。oh,怎么破😯😯

1.1 优化

我们在从网上获取到数据后,就立马根据数据计算cell的高度,并为model添加cellHeight的属性(保存cell的高度),在heightForRowAtIndexPath的方法中直接取来用就好了,不用每次去计算了。。哈哈 这样会不会流畅一点呢,事实证明是的😄😄,代码如下

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BTNewsFlashModel *model = _dataArray[indexPath.row];
    return model.cellHeight;
}

在这里,强烈推荐一个好用的第三方UITableView+FDTemplateLayoutCell,只需一句代码,完美、perfect、100分

#import "UITableView+FDTemplateLayoutCell.h"

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:@"reuse identifer" configuration:^(id cell) {
        // Configure this cell with data, same as what you've done in "-tableView:cellForRowAtIndexPath:"
        // Like:
        //    cell.entity = self.feedEntities[indexPath.row];
    }];
}
优化 1.2

根据苹果的描述,UIKit是我们最容易也是最常接触到的框架,而我们使用
add subView添加控件都由UIKit完成,但是UIKit本质上依赖于Core Graphics框架,也是基于Core Graphics框架实现的。所以如果想要完成某些更底层的功能或者追求极致的性能,那么推荐使用Core Graphics完成。如下一部分代码:(完整代码见VVeboTableViewDemo)

- (void)draw{
    if (drawed) {
        return;
    }
    NSInteger flag = drawColorFlag;
    drawed = YES;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        CGRect rect = [_data[@"frame"] CGRectValue];
        UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0);
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        [[UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1] set];
        CGContextFillRect(context, rect);
        
        if ([_data valueForKey:@"subData"]) {
            [[UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1] set];
            CGRect subFrame = [_data[@"subData"][@"frame"] CGRectValue];
            CGContextFillRect(context, subFrame);
            [[UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1] set];
            CGContextFillRect(context, CGRectMake(0, subFrame.origin.y, rect.size.width, .5));
        }
 UIImage *temp = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        dispatch_async(dispatch_get_main_queue(), ^{
            if (flag==drawColorFlag) {
                postBGView.frame = rect;
                postBGView.image = nil;
                postBGView.image = temp;
            }
        });
    });
    [self drawText];
    [self loadThumb];
}

优化1.3

//按需加载 - 如果目标行与当前行相差超过指定行数,只在目标滚动范围的前后指定3行加载。
 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{ 

      NSIndexPath *ip = [self indexPathForRowAtPoint:CGPointMake(0, targetContentOffset->y)]; 
      NSIndexPath *cip = [[self indexPathsForVisibleRows] firstObject];  
      NSInteger skipCount = 8;
     if (labs(cip.row-ip.row)>skipCount) { 
          NSArray *temp = [self indexPathsForRowsInRect:CGRectMake(0, targetContentOffset->y, self.width, self.height)]; 
         NSMutableArray *arr = [NSMutableArray arrayWithArray:temp]; 
         if (velocity.y<0) {
              NSIndexPath *indexPath = [temp lastObject];
              if (indexPath.row+3<datas.count) {
                      [arr addObject:[NSIndexPath indexPathForRow:indexPath.row+1 inSection:0]]; 
                      [arr addObject:[NSIndexPath indexPathForRow:indexPath.row+2 inSection:0]]; 
                      [arr addObject:[NSIndexPath indexPathForRow:indexPath.row+3 inSection:0]];
                }
          } else { 
          NSIndexPath *indexPath = [temp firstObject]; 
          if (indexPath.row>3) { 
              [arr addObject:[NSIndexPath indexPathForRow:indexPath.row-3 inSection:0]]; 
              [arr addObject:[NSIndexPath indexPathForRow:indexPath.row-2 inSection:0]]; 
              [arr addObject:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:0]]; 
           }
     }
    [needLoadArr addObjectsFromArray:arr]; 
   }
}

记得在tableView:cellForRowAtIndexPath:方法中加入判断:
(如果cell不在加载的范围内,就清除掉cell上面的子控件)

if (needLoadArr.count>0&&[needLoadArr indexOfObject:indexPath]==NSNotFound) {
    [cell clear]; 
    return;
  }

滚动速度比较快的时候,只加载一定范围内的cell,不会一次性加载太多,按需加载,可以有效提高流畅度。

总之,优化tableView的流畅度就从三个方面着手

  1. 单独计算cell的高度,并保存下来
  2. 自己使用核心绘图Core Graphics绘制cell上面的子视图
  3. 按需加载cell
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容