在表格视图行中显示来自URL的图像

时间:2019-06-12 17:26:45

标签: swift image tableview

我正在设置一个新应用,用于在表格视图的行列表中显示电影,但是图像无法显示

我有一个电影模型,该模型具有名称和图像URL作为字符串 我也有包含所有电影的所有电影的列表

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let allMovies = Movies()

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return(allMovies.list.count)
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cell")
        cell.imageView?.image = UIImage(contentsOfFile: allMovies.list[indexPath.row].imageURL)
        cell.textLabel?.text = allMovies.list[indexPath.row].name
        return(cell)
    }

1 个答案:

答案 0 :(得分:1)

contentsOfFile功能适合本地网址

cell.imageView?.image = UIImage(contentsOfFile: allMovies.list[indexPath.row].imageURL)

所以(完全不推荐)

if let data = try? Data(contentsOf:URL(string: allMovies.list[indexPath.row].imageURL)!) { // not recommended 
   cell.imageView?.image =  UIImage(data:data)
}

或者最好使用SDWebImage

相关问题