仅在最终位置显示旋转动画 iOS swift

Rotating animation shown at final position only iOS swift

我正在尝试实现自定义 activity 指示器,它是简单的旋转 UIImageView。我有下一个代码

import Foundation
import UIKit

class CatSpinnerAnimation: UIView {

let catImageView: UIImageView = {
    let catImageView = UIImageView()
    catImageView.image = UIImage(named: "CatDateIcon-1024")
    catImageView.translatesAutoresizingMaskIntoConstraints = false
    return catImageView
}()

func startRotating(superView: UIView) {
    superView.addSubview(catImageView)
    UIApplication.shared.beginIgnoringInteractionEvents()
    catImageView.centerXAnchor.constraint(equalTo: superView.centerXAnchor).isActive = true
    catImageView.centerYAnchor.constraint(equalTo: superView.centerYAnchor).isActive = true
    catImageView.widthAnchor.constraint(equalToConstant: 50).isActive = true
    catImageView.heightAnchor.constraint(equalToConstant: 50).isActive = true



    let rotate = CGAffineTransform(rotationAngle: CGFloat.pi)

    UIView.animate(withDuration: 5.0) {
        self.catImageView.transform = rotate
    }

}



func stopRotating(superView: UIView) {
    UIApplication.shared.endIgnoringInteractionEvents()
    catImageView.removeFromSuperview()

}
}

在我的 ViewControllers 中,我实例化了这个 class 的一个实例并调用它的函数

    let catSpinnerAnimation = CatSpinnerAnimation()
    catSpinnerAnimation.startRotating(superView: view)

但这根本不显示旋转动画,只是我的 ImageView 在最终位置(旋转 189 度)。我尝试了许多类型的动画,但仍然没有必要的结果。我将不胜感激任何关于旋转动画正确行为的解释

我认为您可能需要先将视图添加到视图层次结构中,然后才能为其设置动画。尝试将对 UIView.animate() 的调用包装在对 DispatchQueue.main.asyncAfter(deadline: .now() + .01) {}

的调用中

这将使您的视图添加到视图层次结构并在您提交动画之前得到呈现。