无法将图像传递到另一个视图(获取异步后)

时间:2016-11-07 07:13:38

标签: ios swift uiimage tableview

我无法将UIImageViewtableView传递给UIViewController。图像显示在TableView中,但是当我尝试传递到另一个视图时,它会得到nil

下载图片的方法是:

 func loadImageFromUrl(url: String, view: UIImageView){

      // Create Url from string
      let url = NSURL(string: url)!

      // Download task:
      // - sharedSession = global NSURLCache, NSHTTPCookieStorage and NSURLCredentialStorage objects.
      let task = URLSession.shared.dataTask(with: url as URL) { (responseData, responseUrl, error) -> Void in
           // if responseData is not null...
           if let data = responseData{

                // execute in UI thread
                DispatchQueue.main.async {
                     view.image = UIImage(data: data)
                }
           }
      }

      // Run task
      task.resume()
 }

这就是我如何填充我的tableView

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = Bundle.main.loadNibNamed("UIProductTableViewCell", owner: self, options: nil)?.first as! UIProductTableViewCell
    cell.selectionStyle = .none

    //Populating data
    cell.descriptionLabel.text = catalogOfProducts[indexPath.row].name
    cell.priceLabel.text = catalogOfProducts[indexPath.row].regularPrice

    if (catalogOfProducts[indexPath.row].productImageURL == "") {
       cell.productImageView.image = UIImage(named: "noImage")
    }else{
      loadImageFromUrl(url: catalogOfProducts[indexPath.row].productImageURL!, view: cell.productImageView)

    }
    catalogOfProducts[indexPath.row].productImage = cell.productImageView.image
    return cell
}

catalogOfProducts[indexPath.row] 是我将UIImage传递给相应对象的方式。

要通过segue传递数据,我只需传递Product对象:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "productDetailSegue", sender: catalogOfProducts[indexPath.row])
}

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      let productDetailViewController = segue.destination as! ProductDetailViewController
      productDetailViewController.featuredProduct = (sender as? Product)!
 }

3 个答案:

答案 0 :(得分:2)

如需简单管理下载的图像,您可以使用SDWebImage库。

SDWebImage链接:https://github.com/rs/SDWebImage

这个图书馆很好地用路径管理图像。

如何使用SDWebImage:

cell.productImageView.sd_setImageWithURL(NSURL(string: catalogOfProducts[indexPath.row].productImageURL!), placeholderImage:UIImage(imageNamed:"placeholder.png"))

只需将您的图片网址传递到下一个视图,然后使用相同的代码在下一个视图中获取图片。

注意:当您调用上述函数agin时,它不会下载图像agin并返回下载的图像。

希望这会有所帮助。

答案 1 :(得分:1)

关于这个 -

覆盖func prepare(对于segue:UIStoryboardSegue,sender:Any?){       让productDetailViewController = segue.destination为! ProductDetailViewController       productDetailViewController.featuredProduct =(发件人为?产品)!  }

检查发件人中的内容?您只需发送图像名称,然后就可以将其访问下一个视图控制器。

答案 2 :(得分:0)

你无法在iOS中传递视图,我在我的应用中处理这个问题只是传递图像的名称并在新的viewcontroller中重新加载