How to get the indexpath of a custom table view cell when an UIImage inside of it is tapped and captured by UITapGestureRecognizer in prepareForSegue

若如初见. 提交于 2019-11-29 18:13:11

I would suggest that putting the segue inside the table view cell is the wrong place. It belongs in the view controller, with a delegate method invoked on the view controller to perform it.

Declare a protocol in your cell subclass -

protocol MyCustomCellDelegate {
    func imageTappedInCell(cell:MyCustomCell)
}

Then declare a delegate property and use it in your gesture recogniser -

class MyCustomCell {

    weak var delegate : MyCustomCellDelegate?

    ...

   func imageTapped(recognizer:UIGestureRecognizer) {

       if (recognizer.state == .Ended) {
           delegate?.imageTapped(self)
       }

   }

Then in your view controller you can implement the delegate method. In the delegate method you can use the cell to identify the index path

 class MyTableViewController: UIViewController,MyCustomCellDelegate {


     func imageTapped(cell:MyCustomCell) {
         self.performSegueWithIdentifier("toViewBFromThatImage",sender:cell)
     }

     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if( segue.identifier == "toViewBFromThatImage" ){
            let viewBVC = ( segue.destinationViewController as! viewBVC )
            let senderCell=sender as! MyCustomCell
            viewBVC.selectedIndex = self.tableview.indexPathForCell(senderCell)!
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!