简体   繁体   English

UIButton动画扩展

[英]UIButton animation extension

I'm attempting to reduce redundancy of repetitive code that's used throughout an app by creating a standard animation function. 我试图通过创建标准动画功能来减少在整个应用中使用的重复代码的冗余。

My desired outcome is an animation for a button with an optional completion handler. 我希望得到的结果是带有可选完成处理程序的按钮动画。 Here's my code: 这是我的代码:

extension UIButton {  
  func animate(duration: TimeInterval, completion: ((Bool) -> Swift.Void)?) {
    UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 6.0, options: [], animations: {
      self.transform = .identity
    }, completion: completion)
  }
}

On MyViewController , when I call the animation method like this, the segue happens, but the animation does not: MyViewController ,当我像这样调用动画方法时,会发生segue,但动画不会:

myButton.animate(duration: 0.25) { _ in
  self.performSegue(withIdentifier: "mySequeIdentifier", sender: sender)
}

I commented out the self.performSegue to ensure the segue was not hard-wired on the storyboard, and verified it is not. 我注释掉了self.performSegue以确保该segue在情节self.performSegue没有硬接线,并确认不是。

I also tried declaring the animation function with this code: 我还尝试使用以下代码声明动画功能:

func animate(duration: TimeInterval, completion: @escaping (Bool)->Void?) {
    UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 6.0, options: .allowUserInteraction, animations: {
      self.transform = .identity
    }, completion: completion as? (Bool) -> Void)
}

Using that code, nothing happens. 使用该代码,什么都不会发生。 Not even a crash. 甚至没有崩溃。

Thank you for reading. 感谢您的阅读。 I welcome your suggestions re: where my mistake lies. 我欢迎您提出的建议:我的错误所在。

Well its not animating because I think you forgot to give initial transform value to button before calling extension method. 好吧,这不是动画,因为我认为您忘记了在调用扩展方法之前为按钮提供初始转换值。

  myButton.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
myButton.animate(duration: 0.25) { _ in
  self.performSegue(withIdentifier: "mySequeIdentifier", sender: sender)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM