iOS 11.0.1 crash in viewDidLayoutSubviews

825 Views Asked by At

I have several UIViews in my ViewController that are initially hidden. They become unhidden once I get a successful response from Firebase. These initially hidden views have constraints (from Storyboard) that I am modifying in viewDidLayoutSubviews() based on device size.

Up until iOS 11.0, this worked perfect. Perfect = The views remained hidden. Once Firebase returned a value, the views became unhidden and were the correct size based on the constraints I have set in viewDidLayoutSubviews().

From iOS 11.0.1 and up, I'm now crashing in viewDidLayoutSubviews().

fatal error: unexpectedly found nil while unwrapping an Optional value

Here is the code in my viewDidLayoutSubviews() that's causing the crash in only iOS 11.0.1 and up.

override func viewDidLayoutSubviews() {
    if UIScreen.main.bounds.size.height == 736 { // iPhone 8+
        welcomeViewWidthConstant.constant = 160.0
        welcomeViewHeightConstant.constant = 160.0
    }
}

welcomeViewWidthConstant and welcomeViewHeightConstant are the height and width constraints for the view that is not visible until the Firebase response.

And again, the above was working perfect in iOS 11.0

How can I set the constraints (based on device size) in iOS 11.0.1 and above?

2

There are 2 best solutions below

0
Lou Franco On

I am assuming that welcomeViewWidthConstant is an outlet that you declared with a ! (implicitly unwrapped).

If so, I would look at the stack trace that this is being called in -- is it possible the view is not loaded?

Add

guard let self.isViewLoaded else { return }

to the top of the function

But, I also think it's weird that you would change a constraint in didLayout. I would expect that you would call setNeedsUpdateConstraints on the return from Firebase (probably moving to main queue) and then override updateConstraints to do the update.

1
Joe On

Folks, thank you for lending a hand! I actually found the culprit... The connection to the constraint was disconnected within the storyboard. So the @IBOutlet for welcomeViewWidthConstant and welcomeViewHeightConstant was in fact nil. What was throwing me off was my device isn't an iPhone 8+ size, so it slipped through the cracks.