以编程方式添加动画UIView将宽度分成两半

问题描述:

我正在处理非常基本的动画。绿线是主视图的整个宽度,30英尺高,并从屏幕底部到屏幕顶部进行动画处理。以编程方式添加动画UIView将宽度分成两半

有一个触发此动画的按钮。在按下按钮之前,绿色视图为全宽。大!当我按下按钮为其设置动画效果时,视图宽度在开始动画时会分成两半。

这是我有:

类级别

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) 
} 

这是视图看起来像之前按下按钮

Before button is pressed

这是视图看起来像后按下按钮

什么什么After button is pressed

为什么绿色视图的大小减半了,我能做些什么来防止这种情况?

+0

你有没有在'animatedLineView.frame'设置中使用'width:self.view.frame.width'? – ystack

默认情况下一个层的position是中心点,所以当你的动画开始时,它将绿色条的中心移动到左边缘,这就是为什么它看起来像将它切成两半。将您的x值更改为栏的中心,您将停止看到该问题。你也需要调整你的y值来考虑这个中心,而不是原点。

+1

宾果!那就是诀窍。谢谢! – Joe

+0

@Joe如果您好奇,可以在文档中看到关于'position'属性的详细信息:https://developer.apple.com/reference/quartzcore/calayer/1410791-position – creeperspeak

+0

谢谢。调整绿色视图的anchorPoint比补偿实际动画中的中心点更清晰。 – Joe

我的猜测(没有时间去检查,并不能看到的截图也是如此),它不是萎缩,它的移动一边,半隐半现