【发布时间】:2017-06-23 17:48:06
【问题描述】:
目前我正在使用一个按钮来激活 UIView 动画,并且在它的完成块中,我正在使用 CABasicAnimation 将其返回到它的起始位置。动画一开始运行平稳并返回到其原始起点,但是当我再次按下按钮时,动画会自动从原始 UIView 动画结束的位置开始,而它应该从原始起点开始。
class ObjectCreateMoveViewController: UIViewController, CAAnimationDelegate {
let square = UIView()
override func viewDidLoad() {
super.viewDidLoad()
createSquare()
}
func createSquare() {
square.frame = CGRect(x: 10, y: 10, width: 100, height: 100)
square.backgroundColor = UIColor.red
square.layer.borderColor = UIColor.blue.cgColor
square.layer.borderWidth = 4
square.layer.cornerRadius = 2
view.addSubview(square)
}
func transformAnimation () {
let transAnimation = CABasicAnimation(keyPath: "transform.translation")
transAnimation.toValue = NSValue(cgPoint: CGPoint(x: 10, y: 10))
let rotAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotAnimation.toValue = -CGFloat.pi
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy")
scaleAnimation.toValue = NSNumber(value: 1)
let groupTransform = CAAnimationGroup()
groupTransform.duration = 3
groupTransform.delegate = self
groupTransform.beginTime = CACurrentMediaTime()
groupTransform.animations = [transAnimation, rotAnimation, scaleAnimation]
groupTransform.isRemovedOnCompletion = false
groupTransform.fillMode = kCAFillModeForwards
groupTransform.setValue("circle", forKey: "transform")
square.layer.add(groupTransform, forKey: "transform")
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if flag {
//should be (10,10)but when I printed out the ending positions it was (60,60)
square.layer.position.x = 60
square.layer.position.y = 60
print("This is the x point \(square.layer.position.x)")
print("This is the y point \(square.layer.position.y)")
}
}
@IBAction func transformButtonPressed(_ sender: Any) {
UIView.animate(withDuration: 3, delay: 0, options: .curveEaseInOut, animations: {
let translateTransform = CGAffineTransform(translationX: 150, y: 200)
self.square.transform = translateTransform.scaledBy(x: 1.5, y: 1.5).rotated(by: CGFloat.pi/2)
}, completion: { _ in
self.transformAnimation()
})
}
}
【问题讨论】:
-
首先,如果你
print(square.layer.debugDescription)在对其执行任何动画/变换之前,你会看到图层位置是60,60——也就是说,它是中心点而不是左上角-角落。其次,你改造UIView,然后改造UIView的layer。因此,下次您点击按钮时,View 本质上仍处于其翻译的末尾,而不是 layer 的翻译末尾。您的(当前)目标是否只是让它恢复原状? -
@DonMag 是的,我正在尝试将其动画化回原样。我正在测试它是否可以通过移动图层而不是视图来进行
标签: ios swift core-animation uiviewanimation cabasicanimation