如何从动态生成的UITableViewCell中获取图像并将其与segue传递给其他View?

如何从动态生成的UITableViewCell中获取图像并将其与segue传递给其他View?

问题描述:

我有一个UITableViewControllerUITableViewCell在那里动态生成。每个单元格都包含一个imageView,用于填充从我的服务器获取的图像。我使用alamofire_images这样做。我的代码如下:如何从动态生成的UITableViewCell中获取图像并将其与segue传递给其他View?

func tableView(testDetailsPanel: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = testDetailsPanel.dequeueReusableCellWithIdentifier("cell") as! TestDetailsCell 

    let test:SingleTest = self.items[indexPath.row] as! SingleTest 

    if(test.photo != "") { 
     cell.myPhoto.af_setImageWithURL(NSURL(string: test.photo)!) 
    } else { 
     cell.myPhoto.image = UIImage(named: "clusterLarge") 
    } 
    return cell 
} 

我想,既然我下载图像同时显示表,则无需再次下载它的另一屏幕(这是通过点击每个单元访问)上。

所以我的想法是通过segue将图像从特定单元传递到另一个屏幕。但问题是,从方法prepareForSegue我没有访问用户点击的特定单元格。所以我的另一个选择是使用协议。我创建了一个非常简单的一个:

protocol HandlePhoto: class { 
    func setUpBackgroundPhoto(miniature: UIImage) 
} 

,然后在我的家乡班,我想在didSelectRowAtIndexPath方法来使用它:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 
{ 
    let test:SingleTest = self.items[indexPath.row] as! SingleTest 

    let cell = testDetailsPanel.dequeueReusableCellWithIdentifier("cell") as! TestDetailsCell 

    if(test.photo != "") { 
      handlePhoto.setUpBackgroundPhoto(cell.testPhoto.image!) 
      self.performSegueWithIdentifier("testPhotoDetailsSegue", sender: test) 
     } 
    } else { 
     self.performSegueWithIdentifier("testTextDetailsSegue", sender: test) 
    } 

} 

,但此行:

handlePhoto.setUpBackgroundPhoto(cell.testPhoto.image!) 

抛出错误:

fatal error: unexpectedly found nil while unwrapping an Optional value 

所以我的最后一个问题是:如何从用户选择的特定单元格访问照片并将其传递到其他视图(第二次没有下载它)?

+2

你不需要这样做,图像将被缓存在设备中,它不会被下载到下一个屏幕。 –

+0

@ Mr.UB所以你想告诉我,如果在下一个屏幕上我做'myImage.af_setImageWithURL(NSURL(string:test.photo)!)',那么它不会再次下载它,它会立即在那里?它如何知道应该从缓存中显示哪个图像? – user3766930

为什么在didSelectRowAtIndexPath?中使用dequeueReusableCellWithIdentifier?相反,你应该直接将电池使用:

let cell = yourTableView.cellForRowAtIndexPath(indexPath) as! TestDetailsCell 
if let image = cell.testPhoto.image { 
    print(image)//this is what you want. 
} 

你didSelectRowAtIndexPath方法的实现是错误的,与dequeueReusableCellWithIdentifier你获得新的细胞,而不是选定单元格。 试试这个:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 
{ 

    let selectedCell = tableView.cellForRow(at: indexPath) as! TestDetailsCell 

    //this will return downloaded image or "clusterLarge" 
    let image = selectedCell.myPhoto.image 

    // 
    //Make your check on image and extra setup 
    // 

    self.performSegueWithIdentifier("testPhotoDetailsSegue", sender: test) 

}