覆盖 touchesBegan

Override touchesBegan

我目前正在使用 swift 开发 iOS 应用程序。我使用 override 编写了我自己的 tocuhesBegan 和 tochesEnded 函数。现在当我使用 self.button.

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesBegan(touches, withEvent: event)
    for touch in touches {
        var tap = touch as? UITouch
        var touchPoint: CGPoint = tap!.locationInView(self)
        self.touchDown(touchPoint)
    }
}

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesEnded(touches, withEvent: event)
    self.releaseTouch()
}

override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
    super.touchesCancelled(touches, withEvent: event)
}

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesMoved(touches, withEvent: event)
}

func touchDown(point: CGPoint){
    if rippleEffect == true {
        touchView.frame = touchViewInitFrame
        self.addSubview(touchView)
        var touchViewFrameXPosition: CGFloat = point.x - (frame.size.width) / 2
        println("X position = \(touchViewFrameXPosition)")
        var touchViewFrameYPosition: CGFloat = -(self.frame.size.width - self.frame.size.height) / 2
        touchViewFrame = CGRectMake(touchViewFrameXPosition, touchViewFrameYPosition, frame.size.width, frame.size.width)
        UIView.animateWithDuration(0.25, delay: 0.0, options: .CurveEaseInOut, animations: {
            self.touchView.frame = self.touchViewFrame
            }, completion: nil)
    }

}

func releaseTouch(){
    if rippleEffect == true {
        UIView.animateWithDuration(0.0, delay: 0.0, options: .CurveEaseInOut, animations: {
            self.touchView.removeFromSuperview()
            }, completion: nil)
    }
}

它没有转到我在选择器中指定的函数。还有其他人遇到这个问题吗?或者有人知道发生了什么事吗?

这是我遇到问题时使用的代码。它是 UIButton 的子类。

如果您覆盖任何触摸方法,您应该覆盖所有四个 调用 super.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    //your code
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    //your code
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    [super touchesMoved:touches withEvent:event];
    //your code
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
    [super touchesCancelled:touches withEvent:event];
    //your code
}

您的视图和按钮可能有两个不同的句柄,以证明尝试触摸屏幕上的其他任何地方并且您的触摸将被检测到,但是在按下按钮时触摸是句柄并且永远不会传递给其他处理程序。你必须选择,拦截所有消息并处理它是否应该传递给原始句柄 before/after 你做你需要做的,或者实现按钮处理程序并让它向上传递消息链:

From the apple documentation:

Overriding hit-testing ensures that the superview receives all touches because, by setting itself as the hit-test view, the superview intercepts and receives touches that are normally passed to the subview first. If a superview does not override hitTest:withEvent:, touch events are associated with the subviews where they first occurred and are never sent to the superview.