View Animation does not work - ios Swift 3

2019-07-09 00:24发布

I have this piece of code that supposed to give a spring effect to mainView.

But I don't get the desired effect, I only get the Transition style applied to the ViewController via Storyboards.

override func viewDidLoad()
{
    super.viewDidLoad()

    self.statusBarHidden = UIApplication.shared.isStatusBarHidden
    UIApplication.shared.setStatusBarHidden(true, with: .none)


    self.mainView = UIView(frame: CGRect(x: self.view.getWidth/20, y:self.view.getHeight/6, width:self.view.getWidth/1.3 , height: self.view.getHeight/1.3))

    self.mainView.backgroundColor = UIColor.blue
    self.mainView.center.x = self.view.center.x
    self.mainView.center.y = self.view.center.y

    self.mainView.transform = CGAffineTransform(scaleX: 0.8, y: 1.2) // initial view distorted scale so it has a starting point for the animation

    self.view.addSubview(self.mainView)

    UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: [], animations: {
        self.mainView.transform = .identity // get back to original scale in an animated way
    }, completion: nil)
}  

Can you please help in getting the spring effect to mainView?

Thank you

1条回答
相关推荐>>
2楼-- · 2019-07-09 00:48

To work with animation you should understand view controller life circle. This is crucial in case that you describe becouse you should understand when and why to start animation.

Firstly read please about life circle in official documentation.

Code, but try to understand why it now is working :

  class ViewController: UIViewController {

    var mainView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        addMainView()
    }

    override func viewDidAppear(_ animated: Bool) {
       super.viewDidAppear(animated)
       animateMainView()
    }

    func addMainView() {
        self.mainView = UIView(frame: CGRect(x: self.view.frame.width/20, y:self.view.frame.height/6, width:self.view.frame.width/1.3 , height: self.view.frame.height/1.3))

        self.mainView.backgroundColor = UIColor.blue
        self.mainView.center.x = self.view.center.x
        self.mainView.center.y = self.view.center.y

        self.view.addSubview(self.mainView)
    }

    func animateMainView() {

        self.mainView.transform = CGAffineTransform(scaleX: 0.8, y: 1.2) // initial view distorted scale so it has a starting point for the animation

        UIView.animate(withDuration: 0.9, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: [], animations: {
            self.mainView.transform = .identity // get back to original scale in an animated way
        }, completion: nil)
    }
}

Example of the animation:

enter image description here

查看更多
登录 后发表回答