Uibutton动画扩展



我正在尝试通过创建标准动画函数来减少在整个应用程序中使用的重复代码的冗余。

我期望的结果是带有可选完成处理程序的按钮的动画。这是我的代码:

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

MyViewController上,当我调用这样的动画方法时,会发生这种情况,但动画却没有:

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

我发表了self.performSegue的评论,以确保segue在故事板上没有硬连线,并验证它不是。

我还尝试使用此代码声明动画功能:

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

使用该代码,什么也不会发生。甚至都没有崩溃。

感谢您的阅读。我欢迎您的建议回复:我的错误在哪里。

它不动画,因为我认为您忘了在调用扩展方法之前给按钮给按钮提供初始变换值。

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

最新更新