Make a simple fade in animation in Swift?

前端 未结 6 1019
一个人的身影
一个人的身影 2021-01-30 08:08

I am trying to make a simple animation in Swift. It is a fade in.

I attempted:

self.myFirstLabel.alpha = 0
self.myFirstButton.alpha = 0
         


        
6条回答
  •  [愿得一人]
    2021-01-30 08:51

    The problem is that you're trying start the animation too early in the view controller's lifecycle. In viewDidLoad, the view has just been created, and hasn't yet been added to the view hierarchy, so attempting to animate one of its subviews at this point produces bad results.

    What you really should be doing is continuing to set the alpha of the view in viewDidLoad (or where you create your views), and then waiting for the viewDidAppear: method to be called. At this point, you can start your animations without any issue.

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        UIView.animate(withDuration: 1.5) {
            self.myFirstLabel.alpha = 1.0
            self.myFirstButton.alpha = 1.0
            self.mySecondButton.alpha = 1.0
        }
    }
    

提交回复
热议问题