在 ParentViewController 中动态创建 ChildViewController

在函数 viewDidLoad() 中动态创建一个自定义的 DemoViewController 后,设置 DemoViewController 内已经 Outlet 连线的 label 属性时报错:fatal error: unexpectedly found nil while unwrapping an Optional value

Class DemoViewController {
    @IBOutlet weak var test: UILabel!
}

Class MyViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let vc = DemoViewController()
        vc.test.text = "wangmingjun.com" //fatal error: unexpectedly found nil while unwrapping an Optional value
    }
}

简单查了一下原因,原来是 let vc = DemoViewController() 创建的 vc 上的控件没有被初始化,控件的初始化是 StoryBoard 做的;可以使用下面的方法来创建 VC 并设置控件属性:

let controller:MyView = self.storyboard!.instantiateViewControllerWithIdentifier("MyView") as! MyView
controller.ANYPROPERTY=THEVALUE // If you want to pass value
controller.view.frame = self.view.bounds;
controller.willMoveToParentViewController(self)
self.view.addSubview(controller.view)
self.addChildViewController(controller)
controller.didMoveToParentViewController(self)

注意,移除该动态创建的 view 需要使用如下代码:

self.willMoveToParentViewController(nil)
self.view.removeFromSuperview()
self.removeFromParentViewController()

PS 先访问一下 ChildViewController 的 view 才能触发内部控件的初始化,才可以访问控件。

PS 因为是新手,碰到这种问题一头雾水,查了好久才找到解决方法,方法源自 ios – Adding a view controller as a subview in another view controller – Stack Overflow

 

 

Advertisements

分类:iOS

Tagged as: , , ,

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google+ photo

You are commenting using your Google+ account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.