How to fade a UIVisualEffectView and/or UIBlurEffect in and out?

后端 未结 15 1053
故里飘歌
故里飘歌 2020-12-04 08:38

I want to fade a UIVisualEffectsView with a UIBlurEffect in and out:

var blurEffectView = UIVisualEffectView()
blurEffectView = UIVisualEffectView(effect: UI         


        
15条回答
  •  鱼传尺愫
    2020-12-04 09:37

    Here is the solution that I ended up which works on both iOS10 and earlier versions using Swift 3

    extension UIVisualEffectView {
    
        func fadeInEffect(_ style:UIBlurEffectStyle = .light, withDuration duration: TimeInterval = 1.0) {
            if #available(iOS 10.0, *) {
                let animator = UIViewPropertyAnimator(duration: duration, curve: .easeIn) {
                    self.effect = UIBlurEffect(style: style)
                }
    
                animator.startAnimation()
            }else {
                // Fallback on earlier versions
                UIView.animate(withDuration: duration) {
                    self.effect = UIBlurEffect(style: style)
                }
            }
        }
    
        func fadeOutEffect(withDuration duration: TimeInterval = 1.0) {
            if #available(iOS 10.0, *) {
                let animator = UIViewPropertyAnimator(duration: duration, curve: .linear) {
                    self.effect = nil
                }
    
                animator.startAnimation()
                animator.fractionComplete = 1
            }else {
                // Fallback on earlier versions
                UIView.animate(withDuration: duration) {
                    self.effect = nil
                }
            }
        }
    
    }
    

    You can also check this gist to find an example usage.

提交回复
热议问题