UITableViewCell中用SDWebImage往UIImageView中加載圖片時顯示異常,圖片原本不顯示,只有當(dāng)點擊cell或輪動cell后圖片才會出現(xiàn)。而且圖片顯示的大小和UIImageView的大小不符。
- 本來不顯示圖片
- 點擊cell后會顯示圖片
發(fā)現(xiàn)問題在于我把加載圖像的方法寫在了UITableViewCell中給它設(shè)置數(shù)據(jù)的Set方法里。
UITableViewCell中設(shè)置圖片的方法
-(void)setCellData:(HomeDataModel *)cellData{
_cellData = cellData;
[self.imageView sd_setImageWithURL:[NSURL URLWithString:cellData.imageUrl]];
self.titleLabel.text = cellData.titleString;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
HomeTableViewCell *homeCell = [tableView dequeueReusableCellWithIdentifier:HomeTableViewCellID];
homeCell.cellData = self.mainDataArray[indexPath.row];
return homeCell;
}
如果在UITableView的DataSource中加載圖片則不會出現(xiàn)問題
HomeTableViewCell *homeCell = [tableView dequeueReusableCellWithIdentifier:HomeTableViewCellID];
HomeDataModel *dataModel = self.mainDataArray[indexPath.row];
[homeCell.smallImageView sd_setImageWithURL:[NSURL URLWithString:dataModel.imageUrl]];
homeCell.titleLabel.text = dataModel.titleString;
return homeCell;
}
- 如果堅持之前的寫法,要分兩步解決現(xiàn)實異常的問題,首先
- 在執(zhí)行完設(shè)置圖片的方法后調(diào)用[weakSelf setNeedsLayout];方法,應(yīng)為項目用到的AutoLayout所以調(diào)用這個方法,如果使用frame可能需要調(diào)用setNeedsDisplay方法,沒有測試
-(void)setCellData:(HomeDataModel *)cellData{
__weak typeof(self) weakSelf = self;
_cellData = cellData;
self.imageView.image = nil;//解決cell重用導(dǎo)致的顯示圖片不正確
[self.imageView sd_setImageWithURL:[NSURL URLWithString:cellData.imageUrl]completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
[weakSelf setNeedsLayout];
}];
self.titleLabel.text = cellData.titleString;
NSLog(@"%@",[NSThread currentThread]);
}
- 重寫cell的layoutSubview方法,指定ImageView的frame
-(void)layoutSubviews{
[super layoutSubviews];
self.imageView.frame = CGRectMake(0, 0, 80, 101);
}

Snip20170817_2.png

