Search code examples
iosswiftuiblureffect

Blur effect duplicates everytime I open a view


I have a UITabBar, with the sections, "main" and "profile". In profile I use a background image that fills the entire screen, with a blur effect. It works pretty good. When I go back to main and go back again to profile, a new blur effect is added over the first blur effect.

If I place the code corresponding to set the blur effect in viewDidLoad() it works fine, the effect is added just one time. But there's a problem, the blur effect doesn't fill the entire screen. I suppose this is caused because in viewDidLoad nobody knows the frame of the imageView, so it fills a 3/4 parts of the image.

My question is: how can I fix this? supposing it is caused due to the image frame, that is unknown by now. How do I set the frame measures?

If you think it's caused by another thing tell me what can be.

this is the blur code I'm using?

self.picBlurView = UIVisualEffectView(effect: self.picBlur)
self.picBlurView.frame = self.profileSubView.bounds    
self.profileSubView.addSubview(self.picBlurView)

Many thanks.


Solution

  • Since you already have picBlurView as a property, simply check if it exists. If does not exist, then create it and add it. Otherwise do nothing. Do this in viewWillAppear.

    if (self.picBlurView == nil){
      self.picBlurView = UIVisualEffectView(effect: self.picBlur)
      self.picBlurView.frame = self.profileSubView.bounds
      self.profileSubView.addSubview(self.picBlurView)
    }
    

    You probably want to implement the method willAnimateRotationToInterfaceOrientation so that you can reapply the blur effect when rotation takes place if that matters to you. In here you just replace the one you added originally.