滑动垂直手势不适用于 UITableView

Swipe vertical gesture not working with UITableView

我有 UIViewController,我在故事板中向其添加了一个 UITableView,后来我向视图添加了向上滑动手势识别器,但没有任何反应。

这是我的代码

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {

@IBOutlet weak var tableview: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let swipeRegongnizer = UISwipeGestureRecognizer(target: self, action: #selector(self.handleSwipeUp))
    swipeRegongnizer.direction = UISwipeGestureRecognizerDirection.up
    swipeRegongnizer.delegate = self
    tableview.addGestureRecognizer(swipeRegongnizer)
}

func handleSwipeUp(gesture: UISwipeGestureRecognizer) {
        print("swiped up")
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.text = "cell\(indexPath.row)"
    return cell
}
}

1. 实现 UIGestureRecognizerDelegate。 2. 设置委托。

    yourGesture.delegate = self

3. 在您各自的 swift 文件中添加以下函数。

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
}

实现委托方法

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

此方法将允许同时识别 table 视图的平移手势和您的滑动手势

您需要在各自的视图控制器中添加以下委托。

Objective-C

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
  return YES;
}

Swift

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }

解释

当 gestureRecognizer 或 otherGestureRecognizer 对手势的识别会阻止其他手势识别器识别其手势时,将调用此方法。请注意,返回 YES 保证允许同时识别;另一方面,返回 NO 不能保证阻止同时识别,因为其他手势识别器的委托可能 return YES。默认情况下 returns false.