Ios 自定义UIView类未按预期设置动画
我有一个自定义的UIView类,它创建了一个红色背景的正方形,我正试图从左边在它上面放一张绿色的正方形幻灯片。我在主视图中有一个按钮,它将我带到上面的屏幕,但绿色屏幕在它上面没有动画。它只出现在最终结果中。我确实知道,当我更改绿色正方形的初始宽度时,我正在创建这些形状,但没有显示动画 MainViewController.swiftIos 自定义UIView类未按预期设置动画,ios,swift,uiview,Ios,Swift,Uiview,我有一个自定义的UIView类,它创建了一个红色背景的正方形,我正试图从左边在它上面放一张绿色的正方形幻灯片。我在主视图中有一个按钮,它将我带到上面的屏幕,但绿色屏幕在它上面没有动画。它只出现在最终结果中。我确实知道,当我更改绿色正方形的初始宽度时,我正在创建这些形状,但没有显示动画 MainViewController.swift private func configureAnimatedButton() { //let sampleAnimatedButton let sa
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()
}
动画按钮
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()
外部。此外,如果只是对帧设置动画,则不需要layoutifneed
(在有约束时使用)
另外,请确保不要在
viewdiload()
中调用它——此时,视图尚未布局。您在哪里调用sampleAnimatedButton.animatemidlayer()
?@aheze它位于self.view.addSubView(sampleAnimatedButton)
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")
})