Swift

时间:2018-04-10 05:23:33

标签: ios image swift3 uipageviewcontroller

我正在尝试为我的应用编写演练代码。我想根据页面更改图像。我真的不明白为什么,但我无法从imageView更改图像。

WalkThroughViewController:

class WalkThroughViewController: UIPageViewController, UIPageViewControllerDataSource {
   var mockupImage = ["iphoneWT", "iphoneWT2", "iphoneWT3", "iphoneWT4"]

func viewControllerAtIndex(index: Int) -> WalkthroughContentViewController? {
      if index < 0 || index >= mainTitleContent.count {
         return nil
      }
      if let pageContentVC = storyboard?.instantiateViewController(withIdentifier: "WalkthroughContentViewController") as? WalkthroughContentViewController {
         pageContentVC.imageFileName = mockupImage[index]
         return pageContentVC
      }

      return nil
   }
}

WalkthroughContentViewController:

class WalkthroughContentViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!

    // I got an error on this line:
    imageView.image = UIImage(named: imageFileName)
}

我收到此错误消息:

Unexpectedly found nil while unwrapping an Optional value

imageView连接良好,所以我认为应该没问题......

我如何理解并解决这个问题?

编辑(一些截图):

enter image description here

这里是“模型”,但我将其转换为我的代码中的imageView更清晰

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试创建新属性,例如让image = ImageView(),将图像放入其中,然后在viewWillApear中设置imageView,如下图所示:

class WalkThroughViewController: UIPageViewController, UIPageViewControllerDataSource {
   var mockupImage = ["iphoneWT", "iphoneWT2", "iphoneWT3", "iphoneWT4"]

func viewControllerAtIndex(index: Int) -> WalkthroughContentViewController? {
      if index < 0 || index >= mainTitleContent.count {
         return nil
      }
      if let pageContentVC = storyboard?.instantiateViewController(withIdentifier: "WalkthroughContentViewController") as? WalkthroughContentViewController {
         pageContentVC.image = mockupImage[index]
         return pageContentVC
      }
      return nil
   }
}

和WalkthroughContentViewController的代码一样,你的image属性应该在这里:

class WalkthroughContentViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    var image = UIImage()


    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        imageView.image = image
    }
}   

我认为,当您尝试为imageView设置图像时,imageView尚未初始化,您将获得nil。如果我不清楚或者这没有帮助,请告诉我。