【问题标题】:cell.imageview.image not showing image on tablecell.imageview.image 未在表格上显示图像
【发布时间】:2017-07-09 17:26:40
【问题描述】:

我正在从 firebase 获取图像 URL,但是当尝试在桌子上显示时我看不到一个。代码如下。我正在从

将图像保存在 firebase

UIImagePickerController()

 public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

        let cell = tableView.dequeueReusableCell(withIdentifier: "allUsers", for: indexPath) as! allUserCell
        cell.textLabel?.text = allUserData[indexPath.row].name
        cell.detailTextLabel?.text = allUserData[indexPath.row].email

        if let image = allUserData[indexPath.row].image  {
        let url = NSURL(string: image)
        let request = URLRequest(url:url! as URL)

        URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
            if error != nil{
                print(error as Any)
                return
            }
            DispatchQueue.main.async {
                if let image = UIImage(data: data!) {
                    print(image)
                    cell.imageView?.image = image
                }
            }

        }).resume()

    }
        return cell
}
}

打印(图像)行给了我以下信息:

UIImage: 0x60800009b3f0>, {746, 498}

自定义单元类。

class allUserCell:UITableViewCell{
    override init(style:UITableViewCellStyle,reuseIdentifier:String?) {
        super.init(style:.subtitle,reuseIdentifier:reuseIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

【问题讨论】:

  • 尝试打印cell.imageView,看看是否得到nil
  • @Aaron 你的意思是 cell.imageView.image ?
  • 您使用的是自定义UITableViewCell 而不是default 样式UITableViewCell,因此您需要手动将UIImageView 添加到单元格的contentView 中。
  • @Aaron 不这么认为,但我会这样做。

标签: swift uitableview swift3


【解决方案1】:

添加扩展名

extension UIImageView{

    func setImageFromURl(stringImageUrl url: String){

        if let url = NSURL(string: url) {
            if let data = NSData(contentsOfURL: url) {
                self.image = UIImage(data: data)
            }        
        }
    }
}

然后使用 cell.imageView.setImageFromURl((stringImageUrl: imgURL)) // 在参数中以字符串形式提供您的图片 url

希望这会对你有所帮助。万事如意

【讨论】:

  • 如果我使用 if let url = NSURL(string: url),它会给我错误。
  • 你使用的是哪个版本的swift
猜你喜欢
  • 1970-01-01
  • 2013-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多