首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift -向表单元格中的对象添加手势识别器

问Swift -向表单元格中的对象添加手势识别器
EN

Stack Overflow用户
提问于 2015-08-30 03:53:45
回答 3查看 10.7K关注 0票数 10

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

这个问题(UIGestureRecognizer and UITableViewCell issue )似乎是相关的,然而答案在目标C中,不幸的是我只会说swift。

如果有人能帮我把手势识别器添加到表格单元格中的对象(而不是整个表视图),或者甚至可以帮助我将上面的链接翻译成swift,我将不胜感激

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-08-30 05:00:14

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

代码语言:javascript
复制
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!
                }
            }
        }
    }

}
票数 16
EN

Stack Overflow用户

发布于 2015-08-30 04:58:35

这就是你要的。您在问题中提到的解决方案的快速版本

“您可以将其添加到viewDidLoad的表视图中,而不是直接将手势识别器添加到单元格中。

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

代码语言:javascript
复制
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!){


      }
    }
  }
}
票数 2
EN

Stack Overflow用户

发布于 2018-07-22 09:51:31

Swift 4的更新:

代码语言:javascript
复制
let swipeGestueRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(didRecognizeSwipeGestue(_:)))
self.view.addGestureRecognizer(swipeGestueRecognizer)

和选择器:

代码语言:javascript
复制
@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
            }
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32290126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档