常用控件 tableView 的优化
UITableView最核心的思想就是UITableViewCell的重用机制,UITableView只会创建一屏幕(或一屏幕多一点)的UITableViewCell,其他都是从中取出来重用的。每当Cell滑出屏幕时,就会放入到一个集合(或数组)中(这里就相当于一个重用池),当要显示某一位置的Cell时,会先去集合(或数组)中取,如果有,就直接拿来显示;如果没有,才会创建,这样可以减少内存开销。UITableView优化的首要任务是要优化其两个回调方法:tableView:cellForRowAtIndexPath:和tableView:heightForRowAtIndexPath:,UITableView是继承自UIScrollView的,需要先确定它的contentSize及每个Cell的位置,所以UITableView的回调顺序是先多次调用tableView:heightForRowAtIndexPath:以确定contentSize及Cell的位置,然后才会调用tableView:cellForRowAtIndexPath:,从而来显示在当前屏幕的Cell
1、让tableView:cellForRowAtIndexPath:方法只负责赋值,tableView:heightForRowAtIndexPath:方法只负责计算高度
2、我们在Cell上添加系统控件的时候,实质上系统都需要调用底层的接口进行绘制,当我们大量添加控件时,对资源的开销也会很大,所以我们可以索性直接绘制,提高效率
//异步绘制
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));
}
{
//名字
float leftX = SIZE_GAP_LEFT+SIZE_AVATAR+SIZE_GAP_BIG;
float x = leftX;
float y = (SIZE_AVATAR-(SIZE_FONT_NAME+SIZE_FONT_SUBTITLE+6))/2-2+SIZE_GAP_TOP+SIZE_GAP_SMALL-5;
[_data[@"name"] drawInContext:context withPosition:CGPointMake(x, y) andFont:FontWithSize(SIZE_FONT_NAME)
andTextColor:[UIColor colorWithRed:106/255.0 green:140/255.0 blue:181/255.0 alpha:1]
andHeight:rect.size.height];
//时间+设备
y += SIZE_FONT_NAME+5;
float fromX = leftX;
float size = [UIScreen screenWidth]-leftX;
NSString *from = [NSString stringWithFormat:@"%@ %@", _data[@"time"], _data[@"from"]];
[from drawInContext:context withPosition:CGPointMake(fromX, y) andFont:FontWithSize(SIZE_FONT_SUBTITLE)
andTextColor:[UIColor colorWithRed:178/255.0 green:178/255.0 blue:178/255.0 alpha:1]
andHeight:rect.size.height andWidth:size];
}
//将绘制的内容以图片的形式返回,并调主线程显示
UIImage *temp = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
if (flag==drawColorFlag) {
postBGView.frame = rect;
postBGView.image = nil;
postBGView.image = temp;
}
}
//内容如果是图文混排,就添加View,用CoreText绘制
[self drawText];
}}
3、滑动UITableView时,按需加载对应的内容
//按需加载 - 如果目标行与当前行相差超过指定行数,只在目标滚动范围的前后指定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-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:方法中加入判断:
if (needLoadArr.count>0&&[needLoadArr indexOfObject:indexPath]==NSNotFound) {
[cell clear];
return;
}
总结:
- 提前计算并缓存好高度(布局),因为heightForRowAtIndexPath:是调用最频繁的方法;
- 异步绘制,遇到复杂界面,遇到性能瓶颈时,可能就是突破口;
- 滑动时按需加载,这个在大量图片展示,网络加载的时候很管用!
1.行高要缓存 举个简单的例子: 如果现在要显示100个Cell,当前屏幕显示5个。那么全局刷新UITableView时, UITableView会先调用100次tableView:heightForRowAtIndexPath:方法,然后调用5次 tableView:cellForRowAtIndexPath:方法;滚动屏幕时,每当Cell滚入屏幕,都会调用 一次tableView:heightForRowAtIndexPath:和tableView:cellForRowAtIndexPath:方 法。 所以说要提前计算并缓存好高度,因为heightForRowAtIndexPath:是调用最频繁的方法,如果是使用MVVM搭建框架,可以在viewModel中添加行高属性,提前计算好行高.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"app"];
AppModel *appModel = self.apps[indexPath.row];
cell.textLabel.text = appModel.name;
cell.detailTextLabel.text = appModel.download;
// 占位图片
cell.imageView.image = [UIImage imageNamed:@"kk_fruit_link_180px_1186831_easyicon.net"];
// 从图片缓存中取, 如果取不到
if (!self.iconCache[appModel.icon]) {
NSLog(@"没有缓存");
NSString *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
NSLog(@"%@",cache);
NSString *file = [appModel.icon lastPathComponent];
NSString *path = [cache stringByAppendingPathComponent:file];
__block NSData *data = [NSData dataWithContentsOfFile:path];
// 从内存中取,如果取不到
if (data == nil) {
NSLog(@"没有数据");
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
NSBlockOperation *blockOpertion = self.blockOperation[appModel.icon];
// 判断是否被下载,若果没有下载线程
if (blockOpertion == nil) {
NSLog(@"没有数据,没有线程");
blockOpertion = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:appModel.icon];
data = [NSData dataWithContentsOfURL:url];
// 有线程,但没有下载下来的话,删除线程,重新下载 (保证一个图片,只有一个线程来控制)
if (data == nil) {
NSLog(@"下载不下来,需要重新下载");
[self.blockOperation removeObjectForKey:appModel.icon];
return ;
}
// 下载下来的数据,返回图片
UIImage *image = [UIImage imageWithData:data];
// 图片放入缓存
self.iconCache[appModel.icon] = image;
// 数据进行储存
[data writeToFile:path atomically:YES];
// 将图片返回主线程,并赋值UI
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
// cell.imageView.image = self.iconCache[appModel.icon];
// 刷新数据 ,不让数据复用
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
// 下载成功移除操作
[self.blockOperation removeObjectForKey:appModel.icon];
}];
}];
// 添加操作到队列中
[queue addOperation:blockOpertion];
}
}else{
// 如果内存中有数据
NSLog(@"没有缓存,但有数据");
// 取出数据,返回图片
UIImage *image = [UIImage imageWithData:data];
// 图片放入缓存
self.iconCache[appModel.icon] = image;
// UI赋值
cell.imageView.image = self.iconCache[appModel.icon];
}
}
else{
// 如果有缓存。直接赋值
NSLog(@"有缓存");
cell.imageView.image = self.iconCache[appModel.icon];
}
return cell;
}
"UIImageView+WebCache.h"中已经将这部分代码已经封装完全了.
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:appModel.icon] placeholderImage:image];