Search code examples
swiftbuttonblureffectuiblureffect

Remove BlurEffect before to use it with a button


I have a button, when I clicked it my background_image turns in blur effect.

 @IBAction func button_MainClicked2(_ sender: UIButton) {
        if button_MainCenter == button_viajes.center{
            UIView.animate(withDuration: 0.6, animations:

         {

            let blur = UIBlurEffect(style: UIBlurEffectStyle.light)
            let blurView = UIVisualEffectView(effect: blur)
            blurView.frame = self.image_Background.bounds
            self.image_Background.addSubview(blurView)    

        })
        } else {
            UIView.animate(withDuration: 0.6, animations: {
                // I want to remove blur effect as soon as i press the button again.
            })
        }
    }

How can I fix it to remove the effect as soon as I click back the button?


Solution

  • you can add tag to blur view like blurView.tag = 1000 before adding it as subview, and then in animate block

    for view in button_MainCenter.subviews {
        if view.tag == 1000 {
            view.removeFromSuperview()
        }
    }
    

    edit: not sure if it will be animated though. if not you can animate alpha of this view from 1 to 0 and then remove it.

    edit:

     let blur = UIBlurEffect(style: UIBlurEffectStyle.light)
     let blurView = UIVisualEffectView(effect: blur)
     blurView.tag = 1000
     blurView.frame = self.image_Background.bounds
     self.image_Background.addSubview(blurView)