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
}
Your
badgeLeadingConstraintsisnil. Maybe, it's becomingnilafter device rotation. Try to use size classes or just create a new constraint.