解決tableView/collectionView Cell 使用SDWebImage 時閃爍
問題分析
tableView/collectionView Cell 使用SDWebImage 加載cell 中的網(wǎng)絡(luò)圖片時桌粉,會有閃爍發(fā)生。
經(jīng)分析原因,是由于 cell 的重用機制,導(dǎo)致cell 在 Appear 的時候,首先顯示的是原來的圖片舌缤,然后再執(zhí)行 SDWebImage 的加載圖片。
SDWebImage 無論加載緩存圖片或者網(wǎng)絡(luò)圖片都需要一定時間,但這個時間又很短步势,所以會出現(xiàn)閃爍的情況。
那么背犯,我的方案就是針對這方面去解決問題的坏瘩。
解決方案
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CommonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
cell.imageV.image = [UIImage imageNamed:@"placeHolder"];
[cell.imageV sd_setImageWithURL:[NSURL URLWithString:@"indexPathImageUrl"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
cell.imageV.alpha = 0.0;
[UIView transitionWithView:cell.imageV
duration:1.0
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
[cell.imageV setImage:image];
cell.imageV.alpha = 1.0;
} completion:NULL];
}];
return cell;
}
這里主要是這兩行代碼:
1) cell.imageV.image = [UIImage imageNamed:@"placeHolder"];
在cell 重用的時候,首先使用 placeHolder 直接替換掉原來的圖片媳板,形成占位圖(這里直接用空圖片也是可以的桑腮,比如nil,@"")蛉幸。等于直接清除cell 的重用圖破讨,這樣就不會出現(xiàn)原圖了。2)cell TransitionCrossDissolve
[UIView transitionWithView:cell.imageV
duration:1.0
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
[cell.imageV setImage:image];
cell.imageV.alpha = 1.0;
} completion:NULL];
TransitionCrossDissolve 就是系統(tǒng)默認的轉(zhuǎn)場動畫奕纫。讓新圖片替換原來的圖片的過程中出現(xiàn)的是平滑的動畫提陶。這樣就不是閃爍一下,而是整體的動畫替換匹层,這樣效果就會好很多隙笆。
當(dāng)然 duration 時間可以自定義的調(diào)整,我實際用的是0.35.