iOS tableView的圖片快取非同步載入
阿新 • • 發佈:2019-02-12
- (void)loadCellImage {//方法實現實現圖片有快取則載入圖片,無快取則請求圖片並快取下來再載入 NSArray *indexPathsForLoad = [wqTable indexPathsForVisibleRows]; for (NSIndexPath *item in indexPathsForLoad) { NSInteger rowNumberForCell = item.row; NSLog(@"%li",(long)rowNumberForCell); NSLog(@"%li",(unsigned long)[tableDataArray count]); if (rowNumberForCell >[tableDataArray count] -1) { return; } NSString *imageStr =tableDataArray[rowNumberForCell][@"photoFileUrl"]; NSLog(@"%@",imageStr); NSMutableArray *imageArray = [NSMutableArray array]; if([imageStr length]!=0){ NSArray *photoUrl = [imageStr componentsSeparatedByString:MULTI_FILES_SEPARATOR]; for(int i=0;i<photoUrl.count -1;i++){ //顯示圖片 NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[NSString stringWithFormat:@"%@/%@%@",[WiseApplicationViewController getImgBucketDomain],[WiseApplicationViewController getOrganizationId],photoUrl[i]] stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]]; NSString *imageName = [tableDataArray[rowNumberForCell][KimageKey] stringByAppendingString:[NSString stringWithFormat:@".temp"]]; NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]]; if (![[NSFileManager defaultManager] fileExistsAtPath:imageDataPath]) { [imageData writeToFile:imageDataPath atomically:YES]; UIImage *image = [UIImage imageWithData:imageData]; [imageArray addObject:image]; } } [ICTableVieDelegate cellImageDidLoad:item image:imageArray]; } } } #pragma mark - Table View delegate -(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {//拖拽之後 完成減速時執行停止滾動時啟動快取載入圖片程序 if (!tableView.isDragging && !tableView.isDecelerating) { [self performSelectorInBackground:@selector(loadCellImage) withObject:nil]; } } #pragma mark - Scroll View delegate - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {拖拽之後 完成減速時執行啟動快取載入圖片程序 [self performSelectorInBackground:@selector(loadCellImage) withObject:nil]; } - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {//停止滾動時要執行的程式碼 if (!decelerate) { [self performSelectorInBackground:@selector(loadCellImage) withObject:nil]; } }
然後具體子類繼承這個父類,並實現ICTableViewDelegate代理方法