自定义UIView类未按预期进行动画处理

问题描述

我有一个自定义UIView类,该类创建带有红色背景的正方形,并且我试图从左侧在其顶部获得绿色正方形幻灯片。我在主视图中有一个按钮,将我带到上方的屏幕,但绿色屏幕没有对其进行动画处理。它只是出现在最终结果中。我确实知道,当我更改绿色正方形的初始宽度但没有任何动画指示时,我正在创建这些形状。

MainViewController.swift

private func configureAnimatedButton() {
    //let sampleAnimatedButton
    let sampleAnimatedButton = AnimatedButtonView()
    sampleAnimatedButton.center = CGPoint(x: self.view.frame.size.width  / 2,y: self.view.frame.size.height / 2)
    self.view.addSubview(sampleAnimatedButton)
    sampleAnimatedButton.animateMiddleLayer() 
}

AnimatedButton.swift

import Foundation
import UIKit

public class AnimatedButtonView: UIView {
      //initWithFrame to init view from code
    let movingLayer = UIView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    //initWithCode to init view from xib or storyboard
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupView()
    }
    
    //common func to init our view
    private func setupView() {
        //backgroundColor = .red
        self.frame = CGRect(x: 0,y: 0,width: 300,height: 300)
        self.backgroundColor = .red
        movingLayer.frame = CGRect(x: self.frame.maxX,y: self.frame.minY,width: 0,height: 300)
        movingLayer.backgroundColor = .green
        self.addSubview(movingLayer)
    }
    
    public func animateMiddleLayer() {
        UIView.animate(withDuration: 10.0,delay: 1.2,options: .curveEaSEOut,animations: {
            self.layoutIfNeeded()
            var grayLayerTopFrame = self.movingLayer.frame
            grayLayerTopFrame.origin.x = 0
            grayLayerTopFrame.size.width += 300
            self.movingLayer.frame = grayLayerTopFrame
            self.layoutIfNeeded()
        },completion: { finished in
            print("animated")
        })
    }
}

解决方法

在开始之前,应将grayLayerTopFrame移到UIView.animate()之外。另外,如果您只是在为框架设置动画(在有约束的情况下使用它),则不需要layoutIfNeeded

var grayLayerTopFrame = self.movingLayer.frame
grayLayerTopFrame.origin.x = 0
grayLayerTopFrame.size.width += 300
UIView.animate(withDuration: 10.0,delay: 1.2,options: .curveEaseOut,animations: {
    self.layoutIfNeeded()
    self.movingLayer.frame = grayLayerTopFrame
    self.layoutIfNeeded()
},completion: { finished in
    print("animated")
})

此外,请确保您未在​​viewDidLoad()中调用它-那时,视图尚未布置。