表视图图像未加载或不加载DispatchQueue

时间:2018-01-12 04:08:46

标签: swift uitableview asynchronous grand-central-dispatch

我正在使用SDWebImage库将图像作为imageView加载到我的表格单元格中。 我有类似的问题  这post;我的tableView加载但没有图像。当我单击一个单元格然后返回主页面时,图像最终被加载。但是我想要加载图像而不必这样做(没有任何交互)。

但是,删除DispacheQueue.main.async并不能解决问题;图像仍未加载。我读了那个cell.setNeedsLayout()和 cell.layoutIfNeeded()应该有助于解决这个问题,但他们没有。

顺便说一下,

myURLss是我的URL数组

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell")

        DispatchQueue.main.async {
            cell?.imageView?.sd_setImage(with: self.myURLss[indexPath.row])
            cell?.setNeedsLayout()
        }

    return cell!

}

2 个答案:

答案 0 :(得分:2)

我尝试在链接使用SDWebImage Check Project -

https://drive.google.com/open?id=1BQ_3fFvD04BnGa5uRqbAtU4DWGn_Pzpq

我创建了我的自定义单元格类,其中imageView已连接并在TableView的cellFOrRowAt中更新它

class CustomCell: UITableViewCell {

    //My ImageView
    @IBOutlet weak var myImageView: UIImageView!

    override func awakeFromNib()
    {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

我的TableView CellForRowAt

 //Setting cells data
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {

        let cell = self.myTableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! CustomCell

        DispatchQueue.main.async
            {
            cell.myImageView.sd_setImage(with: self.myURLss[indexPath.row], completed: nil)
        }

        return cell
    }

另外,当您使用SDWebImage Library时,它们会向我们提供一组选项

如果代码中的静止图像未显示,请尝试使用下面的行

cell.myImageView.sd_setImage(with: self.myURLss[indexPath.row], placeholderImage: #imageLiteral(resourceName: "malee"), options: .continueInBackground, completed: nil)

希望有所帮助

答案 1 :(得分:0)

您可以在加载图像后重新加载行。

class Foo {
  i = 0;
  constructor() {
    this.clickHandler = this.clickHandler.bind(this);
  }
  clickHandler() {
    console.log(this.i++);
  }
}

const f = new Foo();
window.onclick = () => f.clickHandler();