I have an imageView which has a top constraint IBOutlet called imageViewTopConstraint. In viewWillLayoutSubviews( ) I set the imageViewTopConstraint.constant value. The imageView displays properly for all iPhone models while in portrait mode, which is good.
When I switch to landscape mode, I want to disable the imageViewTopConstraint, so the viewWillLayoutSubviews( ) has the following code:
if UIDevice.current.orientation.isPortrait {
imageViewTopConstraint.constant = (2 * screenHeight) / 3
imageViewTopConstraint.isActive = true
}
else if UIDevice.current.orientation.isLandscape {
imageViewTopConstraint.isActive = false
}
Issue
When I run the application it is initially in portrait mode. When I switch to landscape mode I receive the following fatal error at the line where I set "imageViewTopConstraint.isActive = false" to disable the constraint (line 6 above)
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
Any idea what is going on or what this means?
The problem is that viewWilllayout is called several times.
Second time, you have set the constraint as inactive, which means it has been removed (it will be reinstalled when you set to true).
So one way is to test
if UIDevice.current.orientation.isPortrait {
imageViewTopConstraint.constant = (2 * screenHeight) / 3
imageViewTopConstraint.isActive = true
}
else if UIDevice.current.orientation.isLandscape {
if imageViewTopConstraint != nil { imageViewTopConstraint.isActive = false }
}