在另一个 class 的 scrollView 中添加图像?

Add an image inside a scrollView from another class?

我正在尝试将图像作为子视图添加到存在于另一个 class

中的滚动视图出口

我确实在我的外部 class 中为存在 scrollView 出口的父 class 创建了一个对象

var imageClassName = ImageViewController()

但是每当我尝试将图像添加到滚动视图时

imageClassName.scrollView.addSubview(imageView)

我收到以下错误 "fatal error: unexpectedly found nil while unwrapping an Optional value"

我也试过在最后添加一个可选的,但仍然得到同样的错误

imageClassName.scrollView?.addSubview(imageView)

有什么线索吗?

这(可能)是一个常见的误解。我刚开始的时候也有这个问题。

想象一下,你是一个奇迹般的现实世界产品设计师,而不是 iOS 开发人员。您设计了一个神奇盒子的蓝图,用户可以在其中放入照片,然后滚动浏览它(有点像神奇的拼贴画)。你让 100 人参加焦点小组,95 人说他们会喜欢。然后您将蓝图发送给一家制造公司,该公司生产 100 多种相同的产品。这与您的情况相似。

你的ImageViewController.swift就像蓝图一样。自己创建一个新实例就像在说:"Put an image into the magicBox's blueprints"。 iOS 没有 的想法 UIViewController 和 class ImageViewController 把图片放进去,因为你可以无限次重复使用它。您需要指定哪个一个您想要的(即使您可能只有一个)

因此,您必须:

  1. 进入你的故事板
  2. Select目标ImageViewController
  3. 点击右侧工具栏左数第三个图标
  4. 在 "Storyboard ID" 部分输入一个 ID(如 "ImageVC1")
  5. var imageClassName = ImageViewController()替换为:

    var imageClassName: ImageViewController = self.storyboard!.instantiateViewControllerWithIdentifier("id you entered in step 4") as! ImageViewController

而且你很好!