2016-08-15 4 views
-1

私の目標は、そのセルの画像ビューをタップするときにsegueを実行することです。ボタンにaddTargetを使用すると、エラーは表示されません。ラベルや画像ビューのタップでセルを取得する方法 - 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

なぜスーパービューに2つの '!'がありますか? – keithbhunter

+0

@keithbhunterはボタンでそれを持っていました。それはエラーなしで働く唯一の方法でした – johnniexo88

+0

私はボタンで何が起こっていたのか分かりませんが、バックラップを強制的に解除することはほとんど間違いです。この場合、あなたの 'superview'はおそらくここではnilではありません。そしてこのコードは一度unwrapすれば動作します。しかし、あなたはそれをもう一度解きます。これはおそらくクラッシュする理由です。 – keithbhunter

答えて

2

ポイントとスーパービューで遊んでいるのは本当に好きではありません。何が示唆できるのは、余分なデータを保持できる次のようなUITapGestureRecognizerのクラスを作ることです。あなたのケースでは、インデックスパス

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

だろう。そして、あなたのdidSelectであなたがbeは次のようになり、新しく作成された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

関連する問題