优化技巧一、UITableView加载图片
2017-02-13 本文已影响378人
ISwiftUI
我的想法是TableView滚动的时候不去加载未加载过的图片,停止滚动后再从网络加载。已经加载过得图片,无论什么时候都加载该图片(因为SDWebImage会将加载过得图片缓存下来,再次加载的时候从缓存中取,这样就不用开辟线程下载图片了)
#pragma mark - UITableView Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.datasArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
// cell.textLabel.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
if((self.tableView.isDragging || self.tableView.isDecelerating) && ![self.cellArray containsObject:indexPath]) {
[cell.testImageV sd_setImageWithURL:[NSURL URLWithString:self.datasArray[indexPath.row]] placeholderImage:[UIImage imageNamed:@"icon_abc"]];
// 滚动时取消任务的下载
[cell.testImageV sd_cancelCurrentImageLoad];
return cell;
}
[cell.testImageV sd_setImageWithURL:[NSURL URLWithString:self.datasArray[indexPath.row]] placeholderImage:[UIImage imageNamed:@"icon_abc"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
if (![self.cellArray containsObject:indexPath]) {
[self.cellArray addObject:indexPath];
}
if (image && cacheType == SDImageCacheTypeNone) {
CATransition *transition = [CATransition animation];
transition.type = kCATransitionFade;
transition.duration = 0.3f;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
// weakself.layer
[cell.testImageV.layer addAnimation:transition forKey:nil];
}
}];
return cell;
}
#pragma mark - UITableViewDelegate Methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
[self.tableView reloadData];
}];
[[SDImageCache sharedImageCache] clearMemory];
}
#pragma mark - UIScrollViewDelegate Methods
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
// 慢滑结束触发
if (! decelerate) {
[self reLoad];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
// 慢滑结束触发
[self reLoad];
}
#pragma mark - Private Methods
- (void) reLoad {
// 刷新当前可见的cells
NSArray *arry = [self.tableView indexPathsForVisibleRows];
NSMutableArray *arrToReload = [NSMutableArray array];
for (NSIndexPath *indexPath in arry) {
if (! [self.cellArray containsObject:indexPath]) {
[arrToReload addObject:indexPath];
}
}
// UITableViewRowAnimationFade
[self.tableView reloadRowsAtIndexPaths:arrToReload withRowAnimation:(UITableViewRowAnimationNone)];
}