Crash during device rotation on a view controller

455 Views Asked by At

I've a custom image which I'm setting as badge on a view. On rotation I call a function to change the leading constraints for this image. Following code crashes when device is rotated.

What is the reason for this and how to fix it?

@IBOutlet weak var badgeLeadingConstraints: NSLayoutConstraint!

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    coordinator.animate(alongsideTransition: { context in
        // This is called during the animation
    }, completion: { context in
        self.updateBadgeConstraints()
    })
}

func updateBadgeConstraints() {
    // Crash on following line
    // Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
    self.badgeLeadingConstraints.constant = (UIScreen.main.bounds.size.width / 4) + 34
}
1

There are 1 best solutions below

4
Bohdan Podvirnyi On

Your badgeLeadingConstraints is nil. Maybe, it's becoming nil after device rotation. Try to use size classes or just create a new constraint.