在UIView.transition中意外地发现了Nil

时间:2018-04-12 20:37:12

标签: ios swift

override func viewDidAppear(_ animated: Bool) {
    images = ["gambar1", "gambar2", "gambar3", "gambar4"]
    home?.image = UIImage.init(named: "gambar1")
    timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(onTransition), userInfo: nil, repeats: true)
}

@objc func onTransition() {
    if (photoCount < images.count - 1){
        photoCount = photoCount  + 1;
    }else{
        photoCount = 0;
    }
    UIView.transition(with: self.home, duration: 1, options: .transitionCrossDissolve, animations: {
        self.home.image = UIImage.init(named: self.images[self.photoCount])
    }, completion: nil)
}

注意:

  

在unwarpping一行中的Optional值时未发现nil,   下面:

**UIView.transition(with: self.home, duration: 1, options: .transitionCrossDissolve, animations: {**

有人可以告诉我发生了什么事吗?谢谢

1 个答案:

答案 0 :(得分:0)

转换方法仅接受包装变量,但此处self.home是可选的,因此请if-let进行检查:

UIView.transition(with: self.home, duration: 1, options: .transitionCrossDissolve, animations: {
    self.home.image = UIImage.init(named: self.images[self.photoCount])
}, completion: nil)
  

如果您的图片视图homeIBOutlet,请检查您是否已从故事板正确连接。

     

如果您的图片视图home是根据代码创建的,请检查它是否已初始化并具有正确的值。

if let view = self.home {
    UIView.transition(with: view, duration: 1, options: .transitionCrossDissolve, animations: {
        view.image = UIImage.init(named: self.images[self.photoCount])
    }, completion: nil)
}