Animation to scale and move UIView (swift)

前端 未结 2 367
旧巷少年郎
旧巷少年郎 2021-01-30 16:41

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.

相关标签:
2条回答
  • 2021-01-30 17:17

    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
        })
    }
    
    0 讨论(0)
  • 2021-01-30 17:36

    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:

    0 讨论(0)
提交回复
热议问题