iosswiftsubviewuivisualeffectview

Remove VisualEffectView from subview


I defined a VisualEffectView by using a boolean condition. In this case, when a button is pressed this function is called with active: true

func addVisualEffectView(active: Bool) {
    let blurEffect = UIBlurEffect(style: .dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    if active {
        blurEffectView.alpha = 0.5
        blurEffectView.frame = self.view.frame
        self.view.insertSubview(blurEffectView, at: 2)
    } else {
        blurEffectView.removeFromSuperview()
    }
}

In another button, this function is called again with active: false, it is supposed to remove VisualEffectView subview from the screen, but it doesn't. Could you help me and tell me where the problem is?


Solution

  • If you've added it once, and then you call your function again, it will not remove the previously added view, it will just not add the new UIVisualEffectView. You need to be able to keep track of the view that you've created by keeping using its tag property.

    func addVisualEffectView(active: Bool) {
        if active {
            let blurEffect = UIBlurEffect(style: .dark)
            let blurEffectView = UIVisualEffectView(effect: blurEffect)
            blurEffectView.alpha = 0.5
            blurEffectView.frame = self.view.frame
            blurEffectView.tag = 332211
            self.view.insertSubview(blurEffectView, at: 2)
        } else {
            self.view.viewWithTag(332211)?.removeFromSuperview()
        }
    }