以编程方式添加的 UIView 的动画将宽度分成两半
Animating a programmatically added UIView splits the width in half
我正在制作一个非常基础的动画。一条绿线,占主视图的全宽,高 30 pt,并从屏幕底部到屏幕顶部进行动画处理。
有一个按钮可以触发这个动画。在我按下按钮之前,绿色视图是全宽的。伟大的!当我按下按钮为其设置动画时,视图宽度在开始设置动画时分成两半。
这是我的:
Class级
let animatedLineView = UIView()
let lineAnimation = CABasicAnimation(keyPath: "position")
viewDidLoad
super.viewDidLoad()
animatedLineView.frame = CGRect(x: 0, y: self.view.bounds.height - 30, width: self.view.bounds.width, height: 30)
animatedLineView.backgroundColor = UIColor.green
self.view.addSubview(animatedLineView)
按钮
@IBAction func testBtnPressed(_ sender: UIButton) {
lineAnimation.duration = 5
lineAnimation.fromValue = CGPoint(x: 0, y: self.view.bounds.height)
lineAnimation.toValue = CGPoint(x: 0, y: 0)
lineAnimation.autoreverses = true
lineAnimation.repeatCount = 100
animatedLineView.layer.add(lineAnimation, forKey: nil)
}
这是视图的样子在按下按钮之前
这是视图的样子按下按钮后
为什么绿色视图的大小减半,我该怎么做才能防止这种情况发生?
我的猜测(没时间看,也看不到截图)不是缩小,是移到一边,半隐
默认情况下,层的 position
是中心点,因此当您的动画开始时,它会将绿色条的中心移动到左边缘,这就是它看起来像是将其切成两半的原因.将您的 x 值更改为条形的中心,您将不再看到该问题。您还需要调整 y 值以说明这是中心,而不是原点。
我正在制作一个非常基础的动画。一条绿线,占主视图的全宽,高 30 pt,并从屏幕底部到屏幕顶部进行动画处理。
有一个按钮可以触发这个动画。在我按下按钮之前,绿色视图是全宽的。伟大的!当我按下按钮为其设置动画时,视图宽度在开始设置动画时分成两半。
这是我的:
Class级
let animatedLineView = UIView()
let lineAnimation = CABasicAnimation(keyPath: "position")
viewDidLoad
super.viewDidLoad()
animatedLineView.frame = CGRect(x: 0, y: self.view.bounds.height - 30, width: self.view.bounds.width, height: 30)
animatedLineView.backgroundColor = UIColor.green
self.view.addSubview(animatedLineView)
按钮
@IBAction func testBtnPressed(_ sender: UIButton) {
lineAnimation.duration = 5
lineAnimation.fromValue = CGPoint(x: 0, y: self.view.bounds.height)
lineAnimation.toValue = CGPoint(x: 0, y: 0)
lineAnimation.autoreverses = true
lineAnimation.repeatCount = 100
animatedLineView.layer.add(lineAnimation, forKey: nil)
}
这是视图的样子在按下按钮之前
这是视图的样子按下按钮后
为什么绿色视图的大小减半,我该怎么做才能防止这种情况发生?
我的猜测(没时间看,也看不到截图)不是缩小,是移到一边,半隐
默认情况下,层的 position
是中心点,因此当您的动画开始时,它会将绿色条的中心移动到左边缘,这就是它看起来像是将其切成两半的原因.将您的 x 值更改为条形的中心,您将不再看到该问题。您还需要调整 y 值以说明这是中心,而不是原点。