2016-09-22 11 views
0

私はUITableViewControllerUITableViewCellを動的に生成しています。各セルには、自分のサーバーから取り込まれたイメージで塗りつぶしているimageViewが含まれています。私はalamofire_imagesを使っています。次のように私のコードでは、なりますどのように私は動的に生成されたUITableViewCellから画像を取得し、他のビューにsegueで渡すことができますか?

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回目にダウンロードすることなく)。

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

} 
関連する問題