我可以使用segue prepare函数处理detailViewController中的滚动视图

时间:2017-10-04 12:37:42

标签: ios swift

获取以下错误消息

  

"致命错误:在展开可选值时意外发现nil"

就这一部分而言 所有图像都没问题。

(segue.destination as! DetailViewController).imgView.image = UIImage(named: "horsestar.png")!

下面的代码是整个准备功能

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    if segue.identifier == "dog" {
        let imgView = UIImageView(image: UIImage(named: "dogstar.png")!)
        print("dog")

        (segue.destination as! DetailViewController).scrollView.addSubview(imgView)
    } else if segue.identifier == "horse" {
        print("horse")
        (segue.destination as! DetailViewController).imgView.image = UIImage(named: "horsestar.png")!
        (segue.destination as! DetailViewController).scrollView.addSubview((segue.destination as! DetailViewController).imgView)
    } else if segue.identifier == "bear" {
        let imageView = UIImageView(image: UIImage(named: "bear.png")!)
        print("bear")
    } else if segue.identifier == "eagle" {
        let imageView = UIImageView(image: UIImage(named: "eagle.png")!)
        print("eagle")
    } else {
        let imageView = UIImageView(image: UIImage(named: "rabbit.png")!)
        print("rabbit")
    }
}

2 个答案:

答案 0 :(得分:1)

小心强制解包(!),因为它在运行时传播了很多错误。如果您的代码中不希望nil值,则为用户guard let

在您的代码中:

(segue.destination as! DetailViewController).imgView.image = UIImage(named: "horsestar.png")!

你有两个危险的地方:

  1. segue.destination投放到DetailViewController。如果不可能,请抛出"fatal error: unexpectedly found nil while unwrapping an Optional value"
  2. 加载名称为“horsestar.png”的图片。如果图像未成立,请抛出"fatal error: unexpectedly found nil while unwrapping an Optional value"
  3. 更好地使用guard let(或if let):

    guard let destinationViewController = segue.destination as? DetailViewController else {
        print("unable to get destinationViewController")
        return
    }
    
    guard let image = UIImage(named: "horsestar.png") else {
        print("unable to load image")
        return
    }
    
    destinationViewController.imgView.image = image
    

答案 1 :(得分:0)

else if条件下更改您的代码

else if segue.identifier == "horse" {
    if let toViewController = segue.destination as? DetailViewController {
      toViewController.imgView.image = UIImage(named: "horsestar.png")

     /// your other stuff 
    }
}

还不知道下面的代码你想要什么?

  (segue.destination as! DetailViewController).scrollView.addSubview((segue.destination as! DetailViewController).imgView)