最近優(yōu)化項目中,TableView滑動時不加載,停止滑動才加載圖片,在iOS項目開發(fā)中是非常常見的。
本文章中就不重復(fù)說比較簡單的和一些細節(jié)方面的問題了,只說幾個重要的地方。好了廢話不說了,上代碼?。?!
-
一.在Model模型中添加一個屬性,
/**是否加載網(wǎng)絡(luò)圖片*/ @property(nonatomic,assign)BOOL isLoad; Model的注意事項 -(void)setValue:(id)value forUndefinedKey:(NSString *)key { 你懂得 } -
二.在自定義Cell.h 中聲明一個方法
-(void)setImageWithModel:(HomeViewModel *)model; -
自定義的Cell.m中實現(xiàn)方法
-(void)setImageWithModel:(HomeViewModel *)model { if (model == nil) { [self.iconImgView setImage:[UIImage imageNamed:@"約單頭像加載"]]; }else{ [self.iconImgView wxl_setImageWithURL:[OSSImageKit scale_w80_h80:model.headPhotoUrl] placeholder:@"約單頭像加載" completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { [_iconImgView setContentScaleFactor:[[UIScreen mainScreen] scale]]; _iconImgView.contentMode = UIViewContentModeScaleAspectFill; _iconImgView.clipsToBounds = YES; [model setIsLoad:YES];//加載網(wǎng)絡(luò)圖片//下載 }]; }}
-
三.回到Controller中,在我們請求數(shù)據(jù)的時候,Model額外的設(shè)置屬性
for (NSDictionary *homeDic in dic[@"data"][@"lease"]) { HomeViewModel *model =[[HomeViewModel alloc] init]; [model setValuesForKeysWithDictionary:homeDic]; model.isLoad = NO;//裝到數(shù)組中,先不下載 [self.dataSource addObject:model]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ //讓tableView準(zhǔn)備好后,再顯示 [self loadShowCells]; }); } -
四.cellForRow方法里要做個判斷了
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { HomePublishSkillViewCell * cell = [tableView dequeueReusableCellWithIdentifier:homePublishIdentifier]; if (!cell) { cell = [[HomePublishSkillViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:homePublishIdentifier]; } HomeViewModel * model = self.dataSource[indexPath.row]; if (model.isLoad) { [cell setImageWithModel:model]; }else{ [cell setImageWithModel:nil]; } cell.selectionStyle = UITableViewCellSelectionStyleNone; cell.seperateLine.hidden = indexPath.row == self.dataSource.count - 1 ?YES:NO; return cell; } -
五.cellForRow 也做好判斷了,真正要監(jiān)聽是否加載網(wǎng)絡(luò)圖片的時候到了
pragma mark -- 監(jiān)聽滾動事件
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
ZZLog(@"----%d",decelerate);
if (!decelerate) {
//滑動時,加載占位圖
[self loadShowCells];
}
}
pragma mark -- 監(jiān)聽滾動事件
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
[self loadShowCells];
}
pragma mark -- 加載Cell中網(wǎng)絡(luò)頭像圖片
-(void)loadShowCells{
NSArray * array = [self.mainTableView indexPathsForVisibleRows];
for (NSIndexPath *indexPath in array) {
HomePublishSkillViewCell * cell = (HomePublishSkillViewCell *)[self.mainTableView cellForRowAtIndexPath:indexPath];
HomeViewModel * model = self.dataSource[indexPath.row];
[cell setImageWithModel:model];
}
}
-
至此,有啥不對的地方還請大神們,多多指點!!本人參照 TableView滑動不加載重新整理了一下。