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

后端 未结 1 1321
失恋的感觉
失恋的感觉 2020-12-22 07:06

Ok a lot of variables in the title, sorry I couldn\'t make it any more simpler.

First, I have a custom table cell with descriptions like so

now, wh

相关标签:
1条回答
  • 2020-12-22 07:25

    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)!
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题