我没有找到有关此问题的文章,但没有一个解决我的问题。
就像我说的那样。
我试图将ViewControllerB添加为ViewControllerA的子视图,但是它 抛出类似“ fatal error: unexpectedly found nil while unwrapping an Optional value” 的错误。
ViewControllerB
ViewControllerA
fatal error: unexpectedly found nil while unwrapping an Optional value
下面是代码…
var testVC: ViewControllerB = ViewControllerB(); override func viewDidLoad() { super.viewDidLoad() self.testVC.view.frame = CGRectMake(0, 0, 350, 450); self.view.addSubview(testVC.view); // Do any additional setup after loading the view. }
ViewControllerB只是一个带有标签的简单屏幕。
@IBOutlet weak var test: UILabel! override func viewDidLoad() { super.viewDidLoad() test.text = "Success" // Throws ERROR here "fatal error: unexpectedly found nil while unwrapping an Optional value" }
EDIT
根据用户答案的建议解决方案,ViewControllerA中的ViewControllerB不在屏幕上。灰色边框是我
一些观察:
ViewControllerB()
Interface Builder1z
Interface Builder
instantiateViewController(withIdentifier:
let controller = storyboard!.instantiateViewController(withIdentifier: "scene storyboard id")
You can now access this controller‘s view.
controller
view
addSubview
addChild(controller) controller.view.frame = … // or, better, turn off translatesAutoresizingMaskIntoConstraints and then define constraints for this subview view.addSubview(controller.view) controller.didMove(toParent: self)
translatesAutoresizingMaskIntoConstraints
For more information about why this addChild (previously called addChildViewController) and didMove(toParent:) (previously called didMove(toParentViewController:)) are necessary, see WWDC 2011 video #102 - Implementing UIViewController Containment. In short, you need to ensure that your view controller hierarchy stays in sync with your view hierarchy, and these calls to addChild and didMove(toParent:) ensure this is the case.
addChild
addChildViewController
didMove(toParent:)
didMove(toParentViewController:)
另请参阅 《View Controller编程指南》中的“ 创建自定义容器View Controller ”。
顺便说一句,以上说明了如何以编程方式执行此操作。它 实际上是容易得多,如果您使用界面生成器“容器视图”。
在此处输入图片说明
这样,您就不必担心与这些与收容相关的任何呼叫, Interface Builder会为您解决。
For Swift 2 implementation, see previous revision of this answer.