2016-09-22 50 views
0

我有一個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

回答

0

爲什麼在didSelectRowAtIndexPath?中使用dequeueReusableCellWithIdentifier?相反,你應該直接將電池使用:

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

你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) 

} 
相關問題