iosswiftuiviewanimationuianimation

UIView Animationn in Swift


Can someone tell me what mistake I have done in following code?

 func animateView(view: UIView){
       view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
        UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
            self.view.transform = .identity
        }, completion: nil)
    }

enter image description here

I want animation like this. I read it on some blog but I didn't get how use it. Thanks in advance


Solution

  • The mistake lies in the first line, where you set the transform to a scale of (1, 1):

    view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
    

    CGAffineTransform(scaleX: 1.0, y: 1.0) means a scale with scale factor of 1, i.e. normal scale. This is equivalent to .identity, so you're askibf it to animate a transformation from the identity transform to the identity transform.

    I'm guessing you probably thought (1, 1) meant 1 pixel by 1 pixel?

    You should instead set the scale to (0, 0) initially:

    view.transform = CGAffineTransform(scaleX: 0, y: 0)
    

    Your second mistake is that you are animating self.view, not the parameter view. This is likely a typo.

    so your whole method looks like:

    func animateView(view: UIView){
       view.transform = CGAffineTransform(scaleX: 0, y: 0)
        UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
            view.transform = .identity
        }, completion: nil)
    }