Skip to content

Instantly share code, notes, and snippets.

@gunhansancar
Created February 16, 2017 13:49
Show Gist options
  • Save gunhansancar/a5153cd4df9e81dd95ad04731b4ddf43 to your computer and use it in GitHub Desktop.
Save gunhansancar/a5153cd4df9e81dd95ad04731b4ddf43 to your computer and use it in GitHub Desktop.
In this gist you can find out how to fade in/fade out UIBlurEffect on UIVisualEffectView on iOS 10 and also earlier versions. Also added example ViewController to see how to use them in action. The below snippets are written in Swift3.
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
}
}
}
}
extension UIView {
func makeBlurEffectView(style:UIBlurEffectStyle? = nil) -> UIVisualEffectView{
let blurEffectView = UIVisualEffectView()
if let style = style {
blurEffectView.effect = UIBlurEffect(style: style)
}
blurEffectView.frame = self.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return blurEffectView
}
func addBlurEffectView(sendBack:Bool = false) -> UIVisualEffectView{
let blurEffectView = makeBlurEffectView()
self.addSubview(blurEffectView)
if sendBack {
self.sendSubview(toBack: blurEffectView)
}
return blurEffectView
}
}
class SamplePopupViewController: UIViewController {
var blurEffectView:UIVisualEffectView?
override func viewDidLoad() {
super.viewDidLoad()
blurEffectView = self.view.addBlurEffectView(sendBack: true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.blurEffectView?.fadeInEffect()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.blurEffectView?.fadeOutEffect()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment