ContainerView embedded in ViewController: Outlets are nil

大兔子大兔子 提交于 2019-12-31 00:55:47

问题


As I am trying to update a container view content from its parent view controller with a function.

After updating the initial ViewDidLoad sets. The app crashes. It seems like all Outlets become nil


回答1:


You need to get a reference to the view controller in the container view and then you should have access to all its outlets. Assign a segue identifier to the segue to the container view controller and get a reference when the segue is called.

For example to update a label in the container view controller from a button in the parent view controller.

Parent view controller:

import UIKit

class ViewController: UIViewController {
     var containerVC : ContainerVC!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    }

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    if (segue.identifier == "segueContainer")
        {
            containerVC = segue.destinationViewController as! ContainerVC
        }
    }


@IBAction func butUpdateContainerLabelAction(sender: AnyObject) {
    if containerVC != nil{
           containerVC.lblDemo.text = "some new text"
       }
    }

}

Container View Controller

class ContainerVC: UIViewController {

@IBOutlet weak var lblDemo: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
   }
}


来源:https://stackoverflow.com/questions/33922428/containerview-embedded-in-viewcontroller-outlets-are-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!