【问题标题】:Subclassing UIButton and overriding touch events - not working子类化 UIButton 并覆盖触摸事件 - 不起作用
【发布时间】:2015-06-28 21:33:30
【问题描述】:

我需要一个项目中所有按钮的缩放弹簧动画。 所以我继承了 UIButton 并覆盖了触摸事件函数。

import UIKit

class UIAnimatedButton: UIButton {

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

    UIView.animateWithDuration(0.1, animations: { () -> Void in
        self.transform = CGAffineTransformMakeScale(0.8, 0.8)

    })
    super.touchesBegan(touches, withEvent: event)

}

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


    UIView.animateWithDuration(0.5,
        delay: 0,
        usingSpringWithDamping: 0.2,
        initialSpringVelocity: 6.0,
        options: UIViewAnimationOptions.AllowUserInteraction,
        animations: { () -> Void in
            self.transform = CGAffineTransformIdentity
    }) { (Bool) -> Void in
        super.touchesCancelled(touches, withEvent: event)
    }

}


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

    UIView.animateWithDuration(0.5,
        delay: 0,
        usingSpringWithDamping: 0.2,
        initialSpringVelocity: 6.0,
        options: UIViewAnimationOptions.AllowUserInteraction,
        animations: { () -> Void in
            self.transform = CGAffineTransformIdentity
        }) { (Bool) -> Void in
            super.touchesEnded(touches, withEvent: event)
    }
  }
} 

这在快速点击时效果很好,但是当我长时间触摸按钮(1-2 秒)时,我没有在动作事件中进行修饰。 当我将其切换回常规 UIButton 时,一切正常。

你知道为什么会这样吗?

【问题讨论】:

  • 如果文档没有另外指定,在被覆盖的方法中要做的第一件事就是调用 super.在动画块中调用它有点奇怪。
  • 如果我在动画结束之前调用 super ,动画将不会动画。你有什么方法可以制作这个动画吗?
  • 尝试使用 UIButton 是其子类的 UIControl 类的 beginTrackingWithTouch:withEvent:、continueTrackingWithTouch:withEvent: 和 endTrackingWithTouch:withEvent: 方法,而不是覆盖 UIGestureRecognizer 方法。
  • 这不起作用...动画没有被动画化

标签: ios swift uibutton uiviewanimation


【解决方案1】:

我没有在 touchesCancelled 和 touchesEnded 方法的完成块中调用 super,而是在其中调用了 self.sendActionsForControlEvents(UIControlEvents.TouchUpInside)。

【讨论】:

    【解决方案2】:

    目前还不确定具体原因,但您需要在动画外调用super.touchesEnded(touches, with: event)

    所以(斯威夫特 5)

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        UIView.animate(withDuration: 0.5,
            delay: 0,
            usingSpringWithDamping: 0.2,
            initialSpringVelocity: 6.0,
            options: UIView.AnimationOptions.allowUserInteraction,
            animations: { () -> Void in
                self.transform = CGAffineTransform.identity
            }) { (Bool) -> Void in
        }
        super.touchesEnded(touches, with: event)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      相关资源
      最近更新 更多