Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - add gesture recognizer to object in table cell

I'm attempting to add a gesture recognizer to an object (an image, specifically) in a table view cell. Now, I'm familiar with gesture recognizers, but am left slightly confused as to how to set this up. The actual table cell doesn't have a viewDidLoad method, so I don't think I can declare the gesture recognizer there.

This question (UIGestureRecognizer and UITableViewCell issue ) seems to be related, however the answer is in objective C, and unfortunately I'm only fluent in swift.

If anybody could perhaps help me out on how I'd go about adding a gesture recognizer to an object in a table cell (NOT the whole tableview), or even perhaps aid me in translating the answer from the above link to swift, I'd be grateful

like image 275
dan martin Avatar asked Aug 29 '15 19:08

dan martin


2 Answers

Here's a quick Swift-translation of the linked post's solution, adding the swipe gesture recognizer to the UITableView and then determining which cell the swipe happened on:

class MyViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        var recognizer = UISwipeGestureRecognizer(target: self, action: "didSwipe")
        self.tableView.addGestureRecognizer(recognizer)
    }

    func didSwipe(recognizer: UIGestureRecognizer) {
        if recognizer.state == UIGestureRecognizerState.Ended {
            let swipeLocation = recognizer.locationInView(self.tableView)
            if let swipedIndexPath = tableView.indexPathForRowAtPoint(swipeLocation) {
                if let swipedCell = self.tableView.cellForRowAtIndexPath(swipedIndexPath) {
                    // Swipe happened. Do stuff!
                }
            }
        }
    }

}
like image 126
Dan Nichols Avatar answered Nov 19 '22 13:11

Dan Nichols


here you go. Swift version of the solution you mentioned in your question

"Instead of adding the gesture recognizer to the cell directly, you can add it to the tableview in viewDidLoad.

In the didSwipe-Method you can determine the affected IndexPath and cell as follows:"

func didSwipe(gestureRecognizer:UIGestureRecognizer) {
    if gestureRecognizer.state == UIGestureRecognizerState.Ended {
        let swipeLocation = gestureRecognizer.locationInView(self.tableView)
          if let swipedIndexPath = self.tableView.indexPathForRowAtPoint(swipeLocation){
            if let swipedCell = self.tableView.cellForRowAtIndexPath(swipedIndexPath!){


      }
    }
  }
}
like image 2
bpolat Avatar answered Nov 19 '22 12:11

bpolat