如何使tableViewCell同时处理tap和longPress? [英] How to make tableViewCell handle both tap and longPress?

查看:154
本文介绍了如何使tableViewCell同时处理tap和longPress?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我把它放在cellForRowAtIndexPath

I put this in cellForRowAtIndexPath

let longPress = UILongPressGestureRecognizer(target: self, action: #selector(CalorieCountViewController.handleLongPress))
cell.addGestureRecognizer(longPress)
longPress.cancelsTouchesInView = true
let tapPress = UITapGestureRecognizer(target: self, action: #selector(CalorieCountViewController.handleTapPress))
cell.addGestureRecognizer(tapPress)
tapPress.cancelsTouchesInView = true

并将它们(下面的代码)放在其中,并完全删除了didSelectRowAtIndexPath函数,请使用indexPathForSelectedRow来获取刚刚选择的行用户.

and put these(code below) outside of it, and removed didSelectRowAtIndexPath function entirely, use indexPathForSelectedRow instead to get which row user just selected.

func handleLongPress(sender: UILongPressGestureRecognizer){
    let index = tableView.indexPathForSelectedRow!
    doSomething(index)
}

func handleTapPress(sender: UITapGestureRecognizer){
    let index = tableView.indexPathForSelectedRow!
    doSomethingElse(index)
}

结果证明indexPathForSelectedRow返回nil,但是我确实选择了一行,并且我的代码中任何地方都没有"deselectRowAtIndexPath".

Turns out indexPathForSelectedRow returns nil, but I did select a row, and there is no "deselectRowAtIndexPath" anywhere in my code.

推荐答案

请勿将UILongPressGestureRecognizer添加到Cell.将其添加到viewDidLoad

Don't add the UILongPressGestureRecognizer to Cell. Add it to UITableView in viewDidLoad

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

通过

func handleLongPress(sender: UILongPressGestureRecognizer){
    if longPressGestureRecognizer.state == UIGestureRecognizerState.Began {
         let touchPoint = longPressGestureRecognizer.locationInView(yourTableView)
         if let indexPath = yourTableView.indexPathForRowAtPoint(touchPoint) {
        // your code here, get the row for the indexPath or do whatever you want
         }
    }
}

使用didSelectRowAtIndexPath代替UITapGestureRecognizer是更好的方法

这篇关于如何使tableViewCell同时处理tap和longPress?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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