UITableViewCell中用SDWebImage往UIImageView中加載圖片時顯示異常

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)實異常的問題,首先
  1. 在執(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]);
}
  1. 重寫cell的layoutSubview方法,指定ImageView的frame
-(void)layoutSubviews{
    [super layoutSubviews];
    self.imageView.frame = CGRectMake(0, 0, 80, 101);
}
Snip20170817_2.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • UITableViewCell 父類是UIView UITableView的每一行都是一個UITableViewC...
    翻這個墻閱讀 6,820評論 0 1
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,401評論 4 61
  • *面試心聲:其實這些題本人都沒怎么背,但是在上海 兩周半 面了大約10家 收到差不多3個offer,總結(jié)起來就是把...
    Dove_iOS閱讀 27,624評論 30 472
  • UITableViewCell控件空間構(gòu)造 cell的子控件是contentView,contentView的子控...
    CoderZXS閱讀 850評論 0 1
  • 感恩雨露胃恩澤在大地;感恩一年有四季;感恩世界還算和平;感恩家人時刻關(guān)愛和朋友一路相伴;感恩,我還健康活著。 ...
    中華燕閱讀 720評論 1 1

友情鏈接更多精彩內(nèi)容