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

标签 ios swift jquery-animate cabasicanimation

我正在制作一个非常基础的动画。一条绿线,占主视图的全宽,高 30 pt,并从屏幕底部到屏幕顶部进行动画处理。

有一个按钮可以触发这个动画。在我按下按钮之前,绿色 View 是全宽的。伟大的!当我按下按钮为其设置动画时, View 宽度在开始设置动画时分成两半。

这是我所拥有的:

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

这是按下按钮之前 View 的样子

Before button is pressed

这是按下按钮之后 View 的样子

After button is pressed

为什么绿色 View 的大小减半,我该怎么做才能防止这种情况发生?

最佳答案

默认情况下,图层的 position 是中心点,因此当您的动画开始时,它会将绿色条的中心移动到左边缘,这就是为什么它看起来像是将其切入的原因一半。将您的 x 值更改为条形的中心,您将不再看到该问题。您还需要调整您的 y 值以说明这是中心,而不是原点。

关于ios - 以编程方式添加的 UIView 的动画将宽度分成两半,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42566726/

相关文章:

javascript - 将行追加到表格并滚动到页面底部的错误

ios - 右上角的对角线试图在 UIView 上绘制

javascript - 带有按钮的 Jquery 自动 slider

jquery - 使用 jQuery.animate 在 Adob​​e AIR 中制作动画

ios - 使用 nil 必需属性保存上下文时,Core Data 自定义访问器崩溃

ios - 更新 UITableViewCell

ios - 如何过滤 'updateSearchResultsForSearchController' 中的字典数组以使用 Swift 搜索 UITableView

iphone - 角标(Badge),更新商品编号?

iphone - 强制 UIViewController 加载特定方向

ios - 自定义 objective-c 类的新实例中已经有数据了吗?