线程1:致命错误:展开一个可选值时意外地找到nil-ImageView

时间:2018-08-20 13:22:17

标签: ios swift null

我知道这个错误很常见,但是我找不到解决方法。 这是我的一部分代码:使用此代码,我将模糊效果添加到三个UIImageViews

 override func viewWillAppear(_ animated: Bool) {
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
    let blurview = UIVisualEffectView(effect: blurEffect)
    blurview.frame = self.blurbar.bounds
    self.blurbar?.addSubview(blurview)

    let blurEffect2 = UIBlurEffect(style: UIBlurEffectStyle.light)
    let blurview2 = UIVisualEffectView(effect: blurEffect2)
    blurview2.frame = self.home_tessera.bounds
    self.home_tessera?.addSubview(blurview2)


    let blurEffect3 = UIBlurEffect(style: UIBlurEffectStyle.light)
    let blurview3 = UIVisualEffectView(effect: blurEffect3)
    blurview3.frame = self.blurbar2.bounds. **THE ERROR IS HERE: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value**
    self.blurbar2?.addSubview(blurview3)

如果我删除了从blurEffect3self.blurbar2?.addSubview...的所有代码,则错误进入blurview2.frame = self.home_tessera.bounds。我已经检查了所有插座,但错误仍然存​​在。

1 个答案:

答案 0 :(得分:-1)

由于home_tesserablurbar2是可选的,因此请确保它们不是nil

if let tessera = self.home_tessera {
    let blurEffect2 = UIBlurEffect(style: UIBlurEffectStyle.light)
    let blurview2 = UIVisualEffectView(effect: blurEffect2)
    blurview2.frame = tessera.bounds
    tessera.addSubview(blurview2)
}

if let bbar2 = self.blurbar2 {
    let blurEffect3 = UIBlurEffect(style: UIBlurEffectStyle.light)
    let blurview3 = UIVisualEffectView(effect: blurEffect3)
    blurview3.frame = bbar2.bounds
    bbar2.addSubview(blurview3)
}

您可能有else来捕捉home_tesserablurbar2为零的情况:

if let tessera = self.home_tessera {
//...
} else {
//print("home_tessera is nil")
}

或者如果您不想遇到这种情况,请使用optional chaining

blurview2.frame = self.home_tessera?.bounds
//...
blurview3.frame = self.blurbar2?.bounds