子视图控制器上的PanGestureRecognizer

时间:2019-04-24 04:02:13

标签: ios swift uitableview uipangesturerecognizer childviewcontroller

我在子视图控制器的容器视图上设置了PanGestureRecognizer。这本质上是一个抽屉视图,因此我希望子视图控制器能够处理所有滚动,除非子视图控制器的表视图滚动到顶部而用户平移时除外。在这种情况下,我希望容器视图手势识别器可以接管,以便整个子视图控制器可以动画化。我有一个手势识别器的委托,如果它不是一个子视图控制器和容器视图,而只是一个表视图,并且向其添加了平移手势识别器,则它可以完美地工作。现在的方式是,委托在应有的情况下返回true,但是还没有调用handlePan方法?任何想法,将不胜感激。谢谢!

下面的所有代码都在具有容器视图的父级UIViewController中,我将手势识别器应用于该视图。一切都能正确显示,只是不调用手势识别器方法,而是调用了委托。

func setUpItemDetailsController() {
        guard let itemDetailsController = itemDetailsController else { return }
        add(itemDetailsController)
        itemDetailsContainerView.addSubview(itemDetailsController.view)

        let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
        panGestureRecognizer.delegate = self
        itemDetailsContainerView.addGestureRecognizer(panGestureRecognizer)
    }

@objc func handlePan(_ sender: UIPanGestureRecognizer) {
     ...
}

extension MoverScanAndDiscoverResultController: UIGestureRecognizerDelegate {
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        guard let panGestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer else { return true }

        let translation = panGestureRecognizer.translation(in: view).y
        let topLimit = view.bounds.height - self.statusAndNavBarCombinedHeight

        print(itemDetailsTableView.contentOffset.y)

        // Allows for normal UITableView scrolling
        if translation < 0
            && resultCardViewBottomConstraint.constant == topLimit
            || itemDetailsController?.tableView.contentOffset.y ?? 0 > 0 {
            return false
        }

        return true
    }
}

1 个答案:

答案 0 :(得分:0)

您是否尝试过UIGestureRecognizerDelegate函数用于与其他手势识别器同时识别?

class MyViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // etc...

        let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panned(_:)))
        panGestureRecognizer.delegate = self
        self.tableView.addGestureRecognizer(panGestureRecognizer)
    }

    @objc
    func panned(_ sender: UIPanGestureRecognizer) {
        print("Panning")
    }
}

extension MyViewController: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true // obviously this could be more refined if you have other gesture recognizers
    }
}

我没有尝试将手势识别器添加到容器视图中,但是将其直接添加到tableView中对我来说很好。