我有一個UITableViewController
與UITableViewCell
在那裏動態生成。每個單元格都包含一個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
所以我的最後一個問題是:如何從用戶選擇的特定單元格訪問照片並將其傳遞到其他視圖(第二次沒有下載它)?
你不需要這樣做,圖像將被緩存在設備中,它不會被下載到下一個屏幕。 –
@ Mr.UB所以你想告訴我,如果在下一個屏幕上我做'myImage.af_setImageWithURL(NSURL(string:test.photo)!)',那麼它不會再次下載它,它會立即在那裏?它如何知道應該從緩存中顯示哪個圖像? – user3766930