我有一个自定义图像,我在视图上设置为徽章。在旋转时,我调用一个函数来改变该图像的前导约束。以下代码在设备旋转时崩溃。
这是什么原因以及如何解决?
@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
}
你的badgeLeadingConstraints
是nil
。也许,它在设备轮换后变成了nil
。尝试使用大小类或只创建一个新约束。