Marcel Marcel - 6 months ago 70
Swift Question

Animation to scale and move UIView (swift)

I have a UIView, placed in the middle of the screen. When the user presses a button, I want it to move up near top of the screen as it shrinks to about a fifth of its size.

I have tried this:

UIView.animateWithDuration(0.7) { () -> Void in
self.main.transform = CGAffineTransformMakeScale(0.2, 0.2)
self.main.transform = CGAffineTransformMakeTranslation(0, -250)

But for some reason, that only scales the view. I have also tried to put this in the animateWithDuration:

self.main.frame = CGRectMake(self.view.frame.width/2 - 10, 50, 50, 50)

How can I get both animations to work?

Joe Joe

Try this Code:

Note: You can achieve animation in several ways in Swift.Below,Code is Just a simple approach...

class ViewController: UIViewController {

@IBOutlet weak var animationButton: UIButton!
@IBOutlet weak var myView: UIView!

override func 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: 119, y: 20, width: self.myView.frame.width, height: self.myView.frame.height)

        //Frame Option 2:
        // = 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 repeat animation..You can enable by setting into true

        },completion: nil)})



enter image description here