Swift 继承 UIView 时过渡动画不起作用

Swift transition animation does not work when subclassing UIView

在将此动画连接到我的 ViewController 并从 ViewDidAppear 调用后将此动画应用于 UIView、UIButton 或 UILabel 时,效果很好:

 UIView.transition(with: self.myButton, duration: 5, options: .transitionFlipFromRight, animations: nil, completion: nil)

但是,问题是,当我在继承自 UIView 的自定义 class 中输入该动画时,将其设置为故事板中的那个对象,并将 "self" 传递到 "with:"参数,放在AwakeFromNib上,不行:

class myAnimatedView: UIView {

    override func awakeFromNib() {
         self.layoutIfNeeded()
         UIView.transition(with: self, duration: 15, options: .transitionFlipFromRight, animations: nil, completion: nil)}
    }

}

我在 AwakeFromNib 上应用的其他动画在此类子设备上运行良好class - 例如,这很好用:

UIView.animate(withDuration: 5.0, delay: 0.5, usingSpringWithDamping: 0.2, initialSpringVelocity: 5.0, options: UIViewAnimationOptions(rawValue: UInt(0)), animations:({//my animations here}))

我做错了什么?使用 Xcode 9.1,Swift 4. 非常感谢

我觉得你的code/architecture有一些问题:

  1. awakeFromNib 不是触发动画的正确位置,请检查 here
  2. 你说加上这个

    UIView.animate(withDuration: 5.0, delay: 0.5, usingSpringWithDamping: 0.2, initialSpringVelocity: 5.0, options: UIViewAnimationOptions(rawValue: UInt(0)), animations:({//my animations here}))
    

    在你的 awakeFromNib 中很好,但我注意到有 0.5 的延迟,所以视图已经准备好并且在动画启动时被很好地唤醒


最终你可能会使用 didMoveToWindow() 为你的东西自动制作动画 https://developer.apple.com/documentation/uikit/uiview/1622527-didmovetowindow