我有一个UIViewController,我想添加一个Pan Gesture Recognizer,我打算做的是创建另一个处理手势和其他功能的类,因此在init()中,我获得了对UIViewController.view的引用。添加手势识别器,其代表是self。
但问题在于手势的动作没有触发。即使从UIViewController添加时会触发

这是我的代码的片段:

// Initializer of UISwipeView
init(Target target: UIView!) {
    super.init();

    // Keep reference to the given view (target)
    self.target = target;

    // if traget is't nill
    if(target != nil) {
        // Add Pan Gesture Recognizer
        gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(UISwipeView.didPaned))
        gestureRecognizer.delegate = self;
        self.target.addGestureRecognizer(gestureRecognizer);
    }
}


这就是我如何通过UIViewController的viewDidLoad()方法使用它

let swipeView: UISwipeView = UISwipeView(Target: self.view);

最佳答案

您最好将手势识别器添加到swipeView中(也许您应该重命名您的类,因为它看起来像UIKit的一部分,具有您提供的名称),并实现swipeView的委托,所以当用户swipes和UISwipeView.didPaned被调用,然后您通知委托这已经发生。

protocol SwipeViewDelegate: class {
    func userDidSwipe(_ gestureRecognizer: UIPanGestureRecognizer)
}


在SwipeView中:

class SwipeView: UIView {
    weak var delegate: SwipeViewDelegate?

    init(withFrame frame: CGRect, delegate: SwipeViewDelegate) {

        self.delegate = delegate

        super.init(frame: frame)

        // add your gesture recognizer stuff here
        self.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(SwipeView.didPan(_:))))

        // etc, etc
    }

    func didPan(_ gestureRecognizer: UIPanGestureRecognizer) {
        self.delegate?.userDidSwipe(gestureRecognizer)
    }
}


在添加SwipeView的viewController中,您必须实现SwipeViewDelegate协议,并在实例化SwipeView时将自己作为委托传递。

(没有机会实际运行其中任何一种,希望没有错别字,等等)

07-24 09:25