Make a simple fade in animation in Swift?

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

    If you want repeatable fade animation you can do that by using CABasicAnimation like below :

    First create handy UIView extension :

    extension UIView {
    
        enum AnimationKeyPath: String {
            case opacity = "opacity"
        }
    
        func flash(animation: AnimationKeyPath ,withDuration duration: TimeInterval = 0.5, repeatCount: Float = 5){
            let flash = CABasicAnimation(keyPath: animation.rawValue)
            flash.duration = duration
            flash.fromValue = 1 // alpha
            flash.toValue = 0 // alpha
            flash.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
            flash.autoreverses = true
            flash.repeatCount = repeatCount
    
            layer.add(flash, forKey: nil)
        }
    }
    

    How to use it:

        // You can use it with all kind of UIViews e.g. UIButton, UILabel, UIImage, UIImageView, ...
        imageView.flash(animation: .opacity, withDuration: 1, repeatCount: 5)
        titleLabel.flash(animation: .opacity, withDuration: 1, repeatCount: 5)
    

提交回复
热议问题