Swift - add gesture recognizer to object in table cell

后端 未结 3 1169
一生所求
一生所求 2020-12-09 20:01

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 con

相关标签:
3条回答
  • 2020-12-09 20:44

    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!
                    }
                }
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-12-09 20:44

    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!){
    
    
          }
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-09 20:49

    Update for Swift 4:

    let swipeGestueRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(didRecognizeSwipeGestue(_:)))
    self.view.addGestureRecognizer(swipeGestueRecognizer)
    

    And the selector:

    @objc func didRecognizeSwipeGestue(_ sender: UISwipeGestureRecognizer) {
    
        if sender.state == UIGestureRecognizerState.ended {
            let location = sender.location(in: self.tableView)
            if let indexPath = tableView.indexPathForRow(at: location) {
                if let cell = self.tableView.cellForRow(at: indexPath) {
                    // todo
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题