简体   繁体   中英

Calling UIView animate withDuration on awakeFromNib does not do the animation

I have a subclass of UIImageView in which I am only creating an animation in the awakeFromNib method but the animation immediately calls the completion block and does not do the animation.

class UISeagull: UIImageView {

    override func awakeFromNib() {
        super.awakeFromNib()
        animate()
    }

    private func animate(){
        UIView.animate(withDuration: 2, delay: 0, options: [.repeat,.autoreverse], animations: {
            self.transform = CGAffineTransform(translationX: 0, y: 7).rotated(by: -20 * (.pi / 180)).scaledBy(x: 0.8, y: 0.8)
        }) { (finish) in
            if finish{
                self.transform = .identity
            }
        }
    }

    deinit {
        self.layer.removeAllAnimations()
    }

}

It immediately enter to the completion block and doesn't enter to if statement also the animation never repeats.

The UIImageView is added in the storyboard and I am using auto layout.

awakeFromNib is too soon. The view doesn't yet have a superview nor does it yet appear on screen.

I would override didMoveToWindow and call animate from there if the window isn't nil .

override func didMoveToWindow() {
    super.didMoveToWindow()

    if window != nil {
        animate()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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