Search code examples
iosswiftuiviewcontrolleruistoryboardsegue

Adding a blur effect on a View Controller after segueing from it to another one modally


I have a view controller(vc1) that contains a button. That button shows another view controller (vc2) modally. presentation style of the segue is set to over current context.

I've also created a UIVisualEffectView on a vc1 programatically (it covers the whole vc1's view).

Now, I need to set a visual effect's effect to UIBlurEffect, but after the vc2 is shown modally (which view's backgroundColour is set to clear, so vc1 is still visible behind vc2).

Is it possible to achieve without having to write a custom view controller transition and if so, how this could be done? If you know how to do this, I would appreciate any help or suggestions.


Solution

  • Blur transition does not come by default in iOS. So you need to customise code.
    A simple solution would be to add a subview :

    Add the following code while transitioning to vc2 :

    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
    blurEffectView = UIVisualEffectView(effect: blurEffect)    // Global variable
    blurEffectView.frame = view.bounds
    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    self.view.addSubview(blurEffectView)
    
    NotificationCenter.default.addObserver(self, selector: #selector(self.removeBlurView), name: NSNotification.Name(rawValue: "removeBlurView"), object: nil)  
    

    Function for removing blur view (in vc1) :

    func removeBlurView()
    {
        NotificationCenter.default.removeObserver(self)
        blurEffectView.removeFromSuperview()
    }  
    

    Add following in vc2 when you dismiss vc2 :

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "removeBlurView"), object: nil)
    

    There are other ways to accomplish this as stated in Ray's tutorial and a closely related tutorial