我不能使用touchesBegan / Moved / Ended和UITapGestureRecognizer

时间:2016-02-02 11:39:56

标签: objective-c swift cocoa-touch uigesturerecognizer

是否无法同时使用这两种方法。最初,我在我的ViewController中覆盖(Swift)touchesBegan / Moved / Ended。

现在,我想在特定情况下为某些视图添加TapGestureRecognizer,但选择器/动作永远不会被触发。

class ViewController: UIViewController, UIGestureRecognizerDelegate {
...
func addTapGesturesOnNumberPadDisplay() {
    if tapGestureRecognizerNumberPadView == nil {
        tapGestureRecognizerNumberPadView = UITapGestureRecognizer(target: self, action: "handleTap:")
        tapGestureRecognizerNumberPadView!.delegate = self
        self.numberViewDone?.addGestureRecognizer(tapGestureRecognizerNumberPadView!)
    }
}
...
func handleTap(sender: UITapGestureRecognizer) {
    //never hit

这不可能吗?我是否应该在touchesBegan中实现自己的点击功能,因为我无论如何都要覆盖它,还是有办法在这里使用tapGestureRecognizer?

1 个答案:

答案 0 :(得分:0)

由于您在viewcontroller中覆盖了touchesBegan / Moved / Ended,因此它不会对其他子视图中的点按手势产生任何影响。理想情况下它应该工作。请检查下面的代码,按预期工作。

class ViewController: UIViewController, UIGestureRecognizerDelegate {

@IBOutlet weak var categoryScrollView: UIScrollView!
var customView: UIView!
var tapGestureRecognizerNumberPadView : UITapGestureRecognizer?

override func viewDidLoad() {
    super.viewDidLoad()
    customView = UIView()
    customView.frame.origin = CGPointMake(50,50)
    customView.frame.size = CGSizeMake(100, 100)
    customView.backgroundColor = UIColor.blueColor()
    self.view.addSubview(customView)
    addTapGesturesOnNumberPadDisplay()
}

func addTapGesturesOnNumberPadDisplay() {
    if tapGestureRecognizerNumberPadView == nil {
        tapGestureRecognizerNumberPadView = UITapGestureRecognizer(target: self, action: "handleTap:")
        tapGestureRecognizerNumberPadView!.delegate = self
        self.customView?.addGestureRecognizer(tapGestureRecognizerNumberPadView!)
    }
}

func handleTap(sender: UITapGestureRecognizer) {
    print("handleTap")
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {

}

}

请检查'numberViewDone'视图是否有任何其他手势。