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

时间:2019-01-16 17:30:47

标签: swift animation uiimageview rotation

我正在尝试实现自定义活动指示器,该指示器是简单的旋转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()

}
}

在ViewController中,我实例化此类的实例并调用其函数

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

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

1 个答案:

答案 0 :(得分:0)

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

这将使您的视图被添加到视图层次结构中并在提交动画之前进行渲染。