【问题标题】:Use func from different view controller swift快速使用来自不同视图控制器的 func
【发布时间】:2019-02-16 18:29:00
【问题描述】:

我使用故事板来构建布局。我正在尝试从secondViewController 访问firstViewController 中的func,但是当我使用以下代码访问它时,无论使用什么函数或插座,我总是会得到“线程1:致命错误:在展开可选值时意外发现nil”我试图访问我总是得到同样的错误。我错过了什么还是我做错了?

done位于secondViewController

func done(){
    let vc =  firstViewController()
    vc.drawCircle(locationX: 0, locationY: 0)
}

drawCircle位于firstViewController

func drawCircle(locationX:CGFloat, locationY: CGFloat) {
    let path = UIBezierPath(roundedRect: CGRect(x: locationX, y: locationY, width: radius, height: radius), cornerRadius: 50).cgPath
    combinePath.addPath(path)
    layer.path = combinePath

    if thickness>0{
        layer.strokeColor = UIColor(red: rColor, green: gColor, blue: bColor, alpha: 1).cgColor
        layer.fillColor = UIColor.clear.cgColor

        layer.lineWidth = thickness
    }
    imageView.layer.addSublayer(layer)

}

【问题讨论】:

  • 你在使用故事板吗?
  • 显示drawCircle函数的代码,同时指定你是使用storyboards,nibs,还是仅仅在代码中创建视图控制器
  • @Ray_Soham 是的,我正在使用情节提要
  • @Scriptable 我正在使用情节提要,我已经添加了 drawCircle 的代码,请看一下谢谢
  • 好的,我想@mahmut 的回答会解决你的问题

标签: swift


【解决方案1】:

默认构造函数不会从情节提要创建 UI 组件(IBOutlet、IBAction、..)

【讨论】:

    【解决方案2】:

    如果您使用故事板,请为视图控制器提供一个标识符并使​​用它:

    if let firstVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "firstViewController") as? firstViewController {
        firstVC.drawCircle(locationX: 0, locationY: 0)
    }
    

    【讨论】:

    • 嗨,我刚刚尝试过,但它只是给了我“线程 1:信号 SIGABRT”错误,并且在日志中显示“故事板()不包含带有标识符“firstViewController”
    • 你有没有给 Identity Inspector 中的 firstViewController 一个标识符?
    • firstViewController 没有标识符。
    • 我不确定这是否会有所帮助,但在 firstViewController 之前,我实际上有另一个 viewController,名为 viewController。
    • 您必须提供一个标识符。如果您不知道该怎么做,这个答案会有所帮助:stackoverflow.com/a/45723662/5130481
    【解决方案3】:

    问题是由于函数drawCircle 中对imageView 的引用,因为这意味着为了使其运行,firstViewController 必须完全初始化并在屏幕上显示imageView 为“连接到用户界面。

    firstViewControllersecondViewController 是否应该同时出现在屏幕上?

    要解决您的问题,您应该将两个Container Views 拖到您的故事板中。每个容器视图的自定义类(在身份检查器中)应分别为 firstViewController 和 secondViewController。

    然后,当您在屏幕上时,两个控制器都将被初始化,imageView 将被正确连接(隐式展开选项将非零)。 这意味着您将能够安全地调用drawCircle 方法。

    【讨论】:

    • firstViewController 和 secondViewController 不应该同时出现在屏幕上
    • 好的。在这种情况下,您需要使用位置 (0,0) 和 Bool shouldDrawCircle = true 更新共享数据结构(模型对象)中的值。然后在 firstViewController 中,在 viewDidAppear 中调用 drawCircle 方法,然后重置 shouldDrawCircle 布尔值。
    • 我的应用程序还没有完全完成,但我只是尝试了你说的方法,我认为这正是我需要的。非常感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多