在表格视图中同时使用点击手势和长按 [英] Using tap gesture and long press at the same time in Table View

查看:45
本文介绍了在表格视图中同时使用点击手势和长按的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个表格视图,但我似乎无法同时使用常规点击和长按来工作.

I'm building a table view and I cannot seem to get both regular taps and long presses to work.

我已将此代码放在我的 viewDidLoad 中:

I have placed this code in my viewDidLoad:

let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
myTableView.addGestureRecognizer(longPress)

这段代码是我的手势识别器:

and this code is my gesture recognizer:

@objc func handleLongPress(sender: UILongPressGestureRecognizer){
    if UILongPressGestureRecognizer.state == UIGestureRecognizer.State.began {

        let touchPoint = UILongPressGestureRecognizer.location(in: self.myTableView)
        if let indexPath = self.myTableView.indexPathForRowAtPoint(touchPoint) {
            print(indexPath.row)
        }
    }
}

我在 Stack Overflow 上找到了这段代码,但我认为它不是 Swift 4 的最新版本,因为我什至无法在构建失败的情况下运行它.

I have found this code here on Stack Overflow, but I do not think it is up to date for Swift 4 because I can not even run it without the build failing.

推荐答案

UILongPressGestureRecognizer.state 应该是 sender.stateUILongPressGesutreRecognizer.location应该是 sender.location.此外,indexPathForRowAtPoint() 的签名已更新为 indexPathForRow(at:).

UILongPressGestureRecognizer.state should be sender.state and UILongPressGesutreRecognizer.location should be sender.location. Also, the signature for indexPathForRowAtPoint() has been updated to indexPathForRow(at:).

更正的代码:

@objc func handleLongPress(sender: UILongPressGestureRecognizer) {
    if sender.state == .began {
        let touchPoint = sender.location(in: self.myTableView)
        if let indexPath = self.myTableView.indexPathForRow(at:touchPoint) {
            print(indexPath.row)
        }
    }
}

UILongPressGestureRecognizer 是类名,需要调用类实例.

UILongPressGestureRecognizer is a class name, you need to be calling the class instance.

这篇关于在表格视图中同时使用点击手势和长按的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆