Make a simple fade in animation in Swift?

前端 未结 6 1013
一个人的身影
一个人的身影 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

    Swift 5

    Other answers are correct, but in my case I need to handle other properties also (alpha, animate, completion). Because of this, I modified a bit to expose these parameters as below:

    extension UIView {
        /// Helper function to update view's alpha with animation
        /// - Parameter alpha: View's alpha
        /// - Parameter animate: Indicate alpha changing with animation or not
        /// - Parameter duration: Indicate time for animation
        /// - Parameter completion: Completion block after alpha changing is finished
        func set(alpha: CGFloat, animate: Bool, duration: TimeInterval = 0.3, completion: ((Bool) -> Void)? = nil) {
            let animation = { (view: UIView) in
                view.alpha = alpha
            }
        
            if animate {
                UIView.animate(withDuration: duration, animations: {
                    animation(self)
                }, completion: { finished in
                    completion?(finished)
                })
            } else {
                layer.removeAllAnimations()
                animation(self)
                completion?(true)
            }
        }
    }
    

提交回复
热议问题