简体   繁体   English

在视图控制器上旋转设备时崩溃

[英]Crash during device rotation on a view controller

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 badgeLeadingConstraints is nil . 您的badgeLeadingConstraintsnil Maybe, it's becoming nil after device rotation. 也许,在设备旋转后,它变得nil Try to use size classes or just create a new constraint. 尝试使用大小类或仅创建一个新约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM