Vincent Rolea Vincent Rolea - 6 months ago 51
Swift Question

Blur effect does not fill the entire View

I have a View controller that features a full screen UIImageView. When the controller loads, I just set a blur effect over the whole screen. The content mode for the UIImageView is set to scaleAspectFill. I set the blur effect like this:

@IBOutlet weak var previewImage: UIImageView!

override func viewDidLoad() {
super.viewDidLoad()
previewImage.image = userPhoto
let blur = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
blur.frame = self.view.bounds
previewImage.addSubview(blur)
}


when I test the app on an iPhone 6 I get this result:

Iphone Screen Capture

There's an offset on the right an I can't figure out why. The picture underneath if is properly full screened but I can get the blur effect to fit over it...

****EDITED****

I applied the blur effect to the VC's view directly and now it works just fine, but I'd like to know why it doesn't work when I add the subview to the UIImage View...

Answer

I see two possible problems here:

  1. Views are not laid out on the viewDidLoad stage. In this case you can force them to layout manualy:

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.layoutIfNeeded()
        ...
    }
    
  2. You add subview to the previewImage, not to the root view. You must check your storyboard, or fix code:

    override func viewDidLoad() {
         super.viewDidLoad()
         previewImage.image = userPhoto     
         let blur = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
         blur.frame = self.view.bounds
         self.view.insertSubview(blur, aboveSubview: previewImage)
     }