0

I want to create a popup controller in Swift, but I can't pass data from the parent controller to the popup (set label text in pop up)

Code:

let popUpPreload = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popUpOneID") as! PopUpViewController
popUpPreload.delegate = self
popUpPreload.lbTitlePopUp.text = "title"
popUpPreload.tvIntructions.text = "intructions"
self.addChildViewController(popUpPreload)
popUpPreload.view.frame = self.view.frame
self.view.addSubview(popUpPreload.view)
popUpPreload.didMove(toParentViewController: self)

Error in set label popup text.

I refer in link

Pang
  • 9,564
  • 146
  • 81
  • 122
Humyl
  • 143
  • 2
  • 9

1 Answers1

2

You cannot instantiate any ViewController from a story board and then immediately try to set properties on its outlets. They are all nil until ViewDidLoad gets called. When you call instantiate view controller it loads the XML, creates the ViewController and all of its subviews and then uses key-value observing to set all of the outlets to the views it has created. It then calls ViewDidLoad when this process is done.

You need to write to a regular variable on your destination view controller.

    let popUpPreload = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popUpOneID") as! PopUpViewController
    popUpPreload.delegate = self
    popUpPreload.titleText = "title"

Then in the ViewController's ViewdidLoad function you assign the outlet property such as label.text to your variable.

    var titleText = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        label.text = titleText
    }
Josh Homann
  • 15,933
  • 3
  • 30
  • 33