42
votes

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?

2

2 Answers

42
votes

Joe's answer above does exactly as his GIF describes but it doesn't really answer your question since it translates then scales the view (as opposed to both translating and scaling at the same time). Your issue is that you're setting the view's transform in your animation block then immediately overwritting that value with another transform. To achieve both translation and scale at the same time, you'll want something like this:

@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
    })
}
40
votes

You can achieve basic UIView 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() {
    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)})

      }
     } 

Output:

enter image description here