美文网首页
UITableView优化

UITableView优化

作者: 兰章海晏 | 来源:发表于2016-08-01 18:58 被阅读254次

    的接口进行绘制,大量添加控件时,会消耗很大的资源并且也会影响渲染的性能。当使用默认的UITableViewCell并且在它的ContentView上面添加控件时会相当消耗性能。所以目前最佳的方法还是继承UITableViewCell,并重写drawRect方法。

    5.减少多余的绘制工作

    在实现drawRect方法的时候,它的参数rect就是我们需要绘制的区域,在rect范围之外的区域我们不需要进行绘制,否则会消耗相当大的资源

    6.不要给cell动态添加subView

    在初始化cell的时候就添加好,然后根据需要来设置hide属性显示和隐藏

    7.异步化UI,不要阻塞主线程

    我们时常会看到这样一个现象,就是加载时整个页面卡住不动,怎么点都没用,仿佛死机了一般。原因是主线程被阻塞了。所以对于网路数据的请求或者图片的加载,我们可以开启多线程,异步话操作

    8.滑动时按需加载对应的内容

    //按需加载 - 如果目标行与当前行相差超过指定行数,只在目标滚动范围的前后指定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+33) {

    [arr addObject:[NSIndexPath indexPathForRow:indexPath.row-3inSection:0]];

    [arr addObject:[NSIndexPath indexPathForRow:indexPath.row-2inSection:0]];

    [arr addObject:[NSIndexPath indexPathForRow:indexPath.row-1inSection:0]];

    }

    }

    [needLoadArr addObjectsFromArray:arr];

    }

    }

    记得在tableView:cellForRowAtIndexPath:方法中加入判断:

    if(needLoadArr.count>0&&[needLoadArr indexOfObject:indexPath]==NSNotFound) {

    [cell clear];return;

    }

    滑动很快时,只加载目标范围内的cell,这样按需加载(配合SDWebImage),极大提高流畅度。

    最后,对于TableView的优化还有很多方面没有提及,希望大家多多交流~

    参考文章

    https://medium.com/ios-os-x-development/perfect-smooth-scrolling-in-uitableviews-fd609d5275a5#.373u9fh4p

    http://blog.sunnyxx.com/2015/05/17/cell-height-calculation/

    http://southpeak.github.io/blog/2015/12/20/perfect-smooth-scrolling-in-uitableviews/

    相关文章

      网友评论

          本文标题:UITableView优化

          本文链接:https://www.haomeiwen.com/subject/wnxfsttx.html