Search code examples
iosios11swift4xcode9

UIVisualEffectView In LoadVIew()


I'm trying to add visualEffect to a view which is working fine on iOS10 and prior versions... but on iOS 11 it crashing. Error reason is listed below:

 has been added as a subview to <UIVisualEffectView: 0x7feabe90d170; frame = (0 0; 375 812); layer = <CALayer: 0x6000006257c0>>. Do not add subviews directly to the visual effect view itself, instead add them to the -contentView."

I'm using the following code:

 override func loadView() { 
    super.loadView()

    // create the blur view
    let blurView = UIVisualEffectView(effect: effect)
    if let oldView = view {
        blurView.frame = view.frame
        oldView.translatesAutoresizingMaskIntoConstraints = false
        blurView.contentView.addSubview(oldView)
        blurView.contentView.pinParentAllDirections(oldView)
    }
    view = blurView
}

The strange thing is when I add this code in viewDidload it's passing the crash... Anybody please help me understand the main problem or am I missing anything in-terms of iOS11.


Solution

  • We should not call super.loadView() from loadView function.

    https://developer.apple.com/documentation/uikit/uiviewcontroller/1621454-loadview

    If you use Interface Builder to create your views and initialize the view controller, you must not override this method.

    We had something similar and fixed it by also moving the code out of loadView method. as loadView is used to construct the view and not a point in time where you want to customize your view.