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-12-18 09:44:33

问题


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, when a user taps on the cell itself, it would go to View A, however, there is a UITapGestureRecognizer that is connected to the UIImage at the left, which is connected to a segue that goes to View B.

All is fine, but I need some data that is inside the table view cell that I can pass to View B so it can do some stuff once the view is shown.

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

    if(segue.identifier == "toViewA") {

    }else if( segue.identifier == "toViewBFromThatImage" ){

        let viewBVC = ( segue.destinationViewController as! viewBVC )
        ///////sender is UITapGestureRecognizer 
        ///////somehow want to get indexpath here

         viewBVC.selectedIndex = SOMEHOW DIRREVED INDEXPATH
    }
}

Perhaps I should just set something as a tag of UIImage or the gesture object when initializing? Or should I avoid trying to do this in prepareForSegue in the first place?

Still new to this so any advice is greatly appreciated.


回答1:


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)!
        }
    }
}


来源:https://stackoverflow.com/questions/33093596/how-to-get-the-indexpath-of-a-custom-table-view-cell-when-an-uiimage-inside-of-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!