【问题标题】:Using tap gesture and long press at the same time in Table View在表格视图中同时使用轻击手势和长按
【发布时间】:2018-12-14 03:28:07
【问题描述】:

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

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

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

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

@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 来说不是最新的,因为我什至无法在构建失败的情况下运行它。

【问题讨论】:

  • if sender.state == .began {let touchPoint = sender.location(in: self.myTableView)

标签: ios swift uitableview uigesturerecognizer


【解决方案1】:

UILongPressGestureRecognizer.state 应该是 sender.stateUILongPressGesutreRecognizer.location 应该是 sender.location。此外,indexPathForRowAtPoint() 的签名已更新为 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是类名,需要调用类实例。

【讨论】:

  • Swift 4 func indexPathForRow(at point: CGPoint) -> IndexPath? 的语法有所改变if let indexPath = myTableView.indexPathForRow(at: touchPoint) {
猜你喜欢
  • 2012-03-11
  • 2012-08-28
  • 2015-03-19
  • 2016-04-05
  • 2014-01-13
  • 1970-01-01
  • 1970-01-01
  • 2019-02-14
  • 2018-01-11
相关资源
最近更新 更多