2016-08-15 30 views
-1

我的目標是執行segue,當我點擊該單元格的imageview。但是當我在按鈕上使用addTarget時,錯誤不會出現。如何獲得標籤或imageview水龍頭上的單元格 - UITapGestureRecognizer

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
    { 
     cell.imageView.userInteractionEnabled = true 
     let tapImageView = UITapGestureRecognizer(target: self, action: #selector(HomeFeedViewController.tapImageView(_:))) 
     cell.imageView.addGestureRecognizer(tapImageView) 
     return cell as CastleCell 
    } 

func tapImageView(sender: AnyObject) { 
     let center = sender.center 
     let point = sender.superview!!.convertPoint(center, toView:self.tableView) //line of error 
     let indexPath = self.tableView.indexPathForRowAtPoint(point) 
     let cell = self.tableView.cellForRowAtIndexPath(indexPath!) as! CastleCell 

     performSegueWithIdentifier("SegueName", sender: self) 
    } 

錯誤的行let point = ...

錯誤我得到的是:

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

,但是當我在一個按鈕,使用addTarget錯誤不會出現。有什麼可能是錯的?謝謝。

+0

爲什麼在'superview'上有兩個'!'? – keithbhunter

+0

@keithbhunter把它放在一個按鈕上,這是它的工作沒有錯誤的唯一方法 – johnniexo88

+0

嗯,我不知道按鈕上發生了什麼,但背靠背力量解開幾乎肯定是一個壞主意。在這種情況下,你的'superview'可能不在這裏,如果你打開一次,這段代碼就可以工作。但是你第二次解開它,這可能是它崩潰的原因。 – keithbhunter

回答

2

我真的不喜歡玩積分和Superview。可以建議的是爲UITapGestureRecognizer創建一個類,如下所示,它可以容納額外的數據。你的情況這將是一個索引路徑

class CustomGesture: UITapGestureRecognizer { 
    let indexPath:NSIndexPath? = nil 
} 

,然後在didSelect可以索引路徑添加到這是會像新創建CustomGesture類:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
    { 
     cell.imageView.userInteractionEnabled = true 
     let tapImageView = CustomGesture(target: self, action: #selector(HomeFeedViewController.tapImageView(_:))) 
     tapImageView.indexPath = indexPath// Add the index path to the gesture itself 
     cell.imageView.addGestureRecognizer(tapImageView) 
     return cell as CastleCell 
    } 

現在既然你有添加indexPath你不需要玩超級視圖,你可以像這樣訪問單元格:

func tapImageView(gesture: CustomGesture) { 

     let indexPath = gesture.indexPath! 
     let cell = self.tableView.cellForRowAtIndexPath(indexPath!) as! CastleCell 

     performSegueWithIdentifier("SegueName", sender: self) 
    } 
+0

哇,非常好。非常感謝!是否有可能不使用自定義類(CustomGesture)? – johnniexo88

+0

如果您想通過手勢傳遞額外的數據,您可能不得不這樣做。但這種方式更加清潔。 – Harsh

相關問題