【问题标题】:Custom UIView class is not animating as expected自定义 UIView 类未按预期设置动画
【发布时间】:2021-01-30 12:30:28
【问题描述】:

我有一个自定义 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")
        })
    }
}

【问题讨论】:

  • 你在哪里打电话sampleAnimatedButton.animateMiddleLayer()
  • @aheze 它在self.view.addSubView(sampleAnimatedButton)

标签: ios swift uiview


【解决方案1】:

在开始之前,您应该将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() 中调用它——那时,视图还没有布局。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 2018-07-25
    相关资源
    最近更新 更多