0
votes

I'm implementing a blur effect on a view (with Swift 4.1, Xcode 9.3) with the following code:

myXib - loads the nib view and adds the blur subview

func setup() {
    // load xib view
    Bundle.main.loadNibNamed("myXib", owner: self, options: nil)
    self.view.frame = bounds
    self.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    self.addSubview(self.view)

    // create blur effect
    let blurEffect = UIBlurEffect(style: .light)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = blurView.bounds
    blurView.translatesAutoresizingMaskIntoConstraints = false
    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    blurView.insertSubview(blurEffectView, at: 0)
    isBlurShowing = true
}

I use a simple toggle button that calls show() or hide() functions.

func hide() {
    blurView.isHidden = true
    blurView.alpha = 0
    isBlurShowing = false
}

func show() {
    blurView.isHidden = false
    blurView.alpha = 1
    isBlurShowing = true
}

The sample myXib looks like this:

enter image description here

where the grey area is the blurView (set to Clear Color normally, only set to grey here for descriptive purposes.)

For a view (orange) under the blurView but inside the Xib the hide() function works correctly but for the view (blue) under the Xib view the blur effect remains.

With blur on (.isHidden = false, .alpha = 1)

blur on

with blur off ((.isHidden = true, .alpha = 0)

enter image description here

The blur effect is less when turned off but it is still present. What am I doing wrong?

Thanks in advance.

1

1 Answers

0
votes

Ok, figured this out.

The issue is that I was creating a second blur layer at 0 because I was calling it also in an init function by having:

override init (frame : CGRect) {
    super.init(frame: frame)
    setup()
}

required init? (coder aDecoder : NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

Once I removed these the code functioned correctly.