Swift:UIPanGestureRecognizer在从另一个类调用时不起作用

时间:2017-06-29 09:19:12

标签: swift uiviewcontroller delegates action uipangesturerecognizer

我有一个UIViewController,我想添加一个Pan Gesture识别器,我打算做的是创建另一个处理手势和其他功能的类,所以在init()中我得到一个引用UIViewController.view然后我添加手势识别器,其委托是自我。 但问题是手势的动作并未触发。即使它从UIViewController添加时会触发

这是我的代码片段:

float: left

以下是我在UIViewController的viewDidLoad()方法中使用它的方法

// 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);
    }
}

1 个答案:

答案 0 :(得分:0)

您最好将手势识别器添加到swipeView中(也许您应该重命名您的课程,因为它看起来像UIKit的一部分,并且已经给出了它的名称),并实现了一个代表swipeView,所以当用户滑动&调用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时将自己作为委托传递。

(没有任何机会实际运行任何这个,希望没有错别字等)