對於tableview加載大量圖片時,如果不做優化,就會損耗服務器對app的性能也不好,在面試過程中面試官也比較關心這個問題,進行百度一下有以下思路:
1.在tableview正在快速滾動和緩慢滾動時,如果該圖片還沒有被加載,那麼就要給它一個默認圖,否則才進行下載圖片。
注:
sdwebimage對下載的圖片有緩存作用,downImageArray用於存儲那些圖片已經下載過的NSIndxPath,tableView屬性isDragging表示正在快速滾動,isDecelerating表示正在慢速滾動,當tableView 正在滾動而且該cell 的圖片還沒下載的時候直接顯示佔位圖片,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@“cell” forIndexPath:indexPath];
if ((self.tableView.isDragging || self.tableView.isDecelerating) && ![self.downImageArray containsObject:indexPath]) {
cell.iconView.image = [UIImage imageNamed:@“1.jpg”];
return cell;
}
[cell.iconView sd_setImageWithURL:[NSURL URLWithString:_array[indexPath.row]] placeholderImage:[UIImage imageNamed:@“1.jpg”] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (![self.downImageArray containsObject:indexPath]) {
[self.downImageArray addObject:indexPath];
}
}];
return cell;
}
//結束快速滾動,開始慢速滾動 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
if (!decelerate) {
[self reload];
}
}
//慢速滾動結束
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
[self reload];
}
// 數據刷新 - (void)reload {
NSArray *arr = [self.tableView indexPathsForVisibleRows];
//存儲需要下載圖片的indexpath
NSMutableArray *arrToReload = [NSMutableArray array];
for (NSIndexPath *indexPath in arr) {
//判斷該cell的圖片是否已經下載
if (![self.downImageArray containsObject:indexPath]) {
[arrToReload addObject:indexPath];
}
}
[self.tableView reloadRowsAtIndexPaths:arrToReload withRowAnimation:UITableViewRowAnimationNone];
}
//當cell移除界面的時候停止當前正在下載圖片 - (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
TableViewCell *tableViewCell = (TableViewCell *)cell;
[tableViewCell.iconView sd_cancelCurrentImageLoad];
}
2.蘋果官方文檔也有介紹該內容LazyTableImages
(本文有參考:https://www.jianshu.com/p/9e503a81de07)