【问题标题】:How to add swipe up and down to UITableView?如何在 UITableView 中添加上下滑动?
【发布时间】:2020-09-18 19:32:01
【问题描述】:

我已经添加到我的ViewController:

let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(handleGestureToScroll))
swipeUp.direction = .up
swipeUp.cancelsTouchesInView = false
self.view.addGestureRecognizer(swipeUp)
        
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(handleGestureToScroll))
swipeDown.direction = .down
swipeDown.cancelsTouchesInView = false
self.view.addGestureRecognizer(swipeDown)

但是当手势在我的UITableView(这是我的视图的子视图)内时,我的方法handleGestureToScroll 不会被调用。否则,当我删除我的 tableView 时它正在工作。

如何添加此手势以在我的UITableView 中工作?

【问题讨论】:

  • 表格视图如何正常上下滚动并响应向上或向下滑动手势识别器?这些行动似乎难以区分,注定会以一种或另一种方式发生冲突。
  • @matt 但是可以例如为同一个元素添加两个触摸手势,为什么不能添加两个'observables'来滑动?我的方法不是滚动表格,而是在发生时进行一些操作。
  • 我只是说您需要以某种方式在它们之间进行调解,因为它们自然会发生冲突。实际上不可能总是“为同一个元素添加两个触摸手势”;如果在同一个视图上添加两个单击的 UITapGestureRecognizers,会发生什么?

标签: swift uitableview swift5


【解决方案1】:

您可以通过将这些手势添加到所有单元格来解决它:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(handleGestureToScroll))
    swipeUp.direction = .up
    let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(handleGestureToScroll))
    swipeDown.direction = .down
    cell.addGestureRecognizer(swipeUp)
    cell.addGestureRecognizer(swipeDown)
    return cell
}
@objc func handleGestureToScroll() {
    print("swipe is handled")
}

【讨论】:

  • 向 tableView 添加滑动手势的唯一方法是在标题/单元格上添加?
  • 嗯,这就是我目前发现的。也许会有更好的解决方案@ThiagoValente。
猜你喜欢
  • 2021-12-13
  • 2015-03-07
  • 2023-01-16
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多