我有一个UIView,放在屏幕中间。当用户按下按钮时,我希望它向上移动靠近屏幕顶部,因为它缩小到大小的五分之一。
我试过这个:
UIView.animateWithDuration(0.7) { () -> Void in
self.main.transform = CGAffineTransformMakeScale(0.2, 0.2)
self.main.transform = CGAffineTransformMakeTranslation(0, -250)
}
但出于某种原因,这只能缩放视图。我也尝试将它放在animateWithDuration中:
self.main.frame = CGRectMake(self.view.frame.width/2 - 10, 50, 50, 50)
如何让两种动画都能正常工作?
答案 0 :(得分:26)
您可以在 Swift 中以多种方式实现基本UIView animation
。下面的代码只是一个简单的方法......
class ViewController: UIViewController {
@IBOutlet weak var animationButton: UIButton!
@IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// I added seperate colour to UIView when animation move from one animation block to another.So, You can get better understanding how the sequence of animation works.
self.myView.backgroundColor = .red
}
@IBAction func animateButton(_ sender: UIButton) {
UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
//Frame Option 1:
self.myView.frame = CGRect(x: self.myView.frame.origin.x, y: 20, width: self.myView.frame.width, height: self.myView.frame.height)
//Frame Option 2:
//self.myView.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 4)
self.myView.backgroundColor = .blue
},completion: { finish in
UIView.animate(withDuration: 1, delay: 0.25,options: UIViewAnimationOptions.curveEaseOut,animations: {
self.myView.backgroundColor = .orange
self.myView.transform = CGAffineTransform(scaleX: 0.25, y: 0.25)
self.animationButton.isEnabled = false // If you want to restrict the button not to repeat animation..You can enable by setting into true
},completion: nil)})
}
}
<强>输出:强>
答案 1 :(得分:23)
Joe上面的回答与他的GIF描述完全相同,但它并没有真正回答你的问题,因为它翻译然后缩放视图(而不是同时进行翻译和缩放)。您的问题是您在动画块中设置视图的变换,然后立即用另一个变换覆盖该值。要同时实现翻译和扩展,你需要这样的东西:
@IBAction func animateButton(_ sender: UIButton) {
let originalTransform = self.main.transform
let scaledTransform = originalTransform.scaledBy(x: 0.2, y: 0.2)
let scaledAndTranslatedTransform = scaledTransform.translatedBy(x: 0.0, y: -250.0)
UIView.animate(withDuration: 0.7, animations: {
self.main.transform = scaledAndTranslatedTransform
})
}