Swift - 将手势识别器添加到 table 单元格中的对象

Swift - add gesture recognizer to object in table cell

我正在尝试将手势识别器添加到 table 视图单元格中的对象(特别是图像)。现在,我熟悉手势识别器,但对如何设置它有点困惑。实际的 table 单元格没有 viewDidLoad 方法,所以我认为我不能在那里声明手势识别器。

这个问题 (UIGestureRecognizer and UITableViewCell issue ) 似乎是相关的,但答案在 objective C 中,不幸的是我只精通 swift。

如果有人可以帮助我了解如何将手势识别器添加到 table 单元格(不是整个 table 视图)中的对象,或者甚至可以提供帮助我将上面 link 的答案翻译成 swift,我将不胜感激

给你。 Swift 您在问题中提到的解决方案版本

"不是直接将手势识别器添加到单元格,而是将其添加到viewDidLoad中的tableview。

在 didSwipe-Method 中,您可以确定受影响的 IndexPath 和单元格,如下所示:

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


      }
    }
  }
}

这是链接 post 解决方案的快速 Swift 翻译,将滑动手势识别器添加到 UITableView,然后确定滑动发生在哪个单元格上:

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

}

Swift4 的更新:

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

选择器:

@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
            }
        }
    }
}