我正在尝试加载另一个UIViewController
,以便我可以获取其中的IBOutlets
的数据。我正在使用 Swift 和 Sprite-Kit。我所说的 UIViewController 称为 GameViewController。这是我的游戏中加载的第一个东西。然后它会转到我的 GameScene
。这是我尝试实例化我的 GameViewController 的地方。我想这样做是因为我正在使用一个名为 iCarousel
的库,并且我想让它从我的 GameScene
向上移动。但是,iCarousel 只能在 UIViewController
上使用。所以我想在 GameViewController
中调用一个函数,该函数将在 GameScene
中调用。在这个函数中,有一个 NSLayoutConstraint 用来移动轮播。每当我调用这个函数时,它都会说它为零。这是我的一些代码:
在我的GameScene
内:
let storyboard: UIStoryboard = UIStoryboard.init(name: "Main", bundle: nil)
let firstViewController: GameViewController = storyboard.instantiateViewControllerWithIdentifier("Load-up") as! GameViewController
firstViewController.start()
在我的GameViewController
内部:
func start() {
// Constraint
top.constant = 100
UIView.animateWithDuration(2){
self.view.layoutIfNeeded()
}
}
如果您需要更多信息,请随时询问我。提前致谢!
最佳答案
那是因为您的 View Controller 尚未加载其 View 层次结构。仅当有东西向其发送 view
消息时,viewController
才会加载其 View 层次结构。系统将在何时将 View
层次结构放在屏幕上时自行执行此操作。它发生在诸如 prepareForSegue:sender:
和 viewWillAppear:
、 loadView()
、 self.view
之类的调用之后。
所以这里你的outlets
仍然是nil
,因为它还没有加载。
只需尝试强制您的 VC 调用 self.view
,然后访问属性/导出。
编辑:添加了示例代码。
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let firstViewController = storyboard.instantiateViewControllerWithIdentifier("Load-up") as! GameViewController
debugPrint("Printing for the sake of initializing view of VC: \(firstViewController.view)")
firstViewController.start()
关于swift - 实例化 View Controller 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38043876/