我无法将UIImageView
从tableView
传递给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)!
}
答案 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中重新加载