I try to assign a value to a view controller from AppDelegate.swift without success.
My controller is named DestinationsViewController
, and its id in Main.storyboard is destinationsID
. DestinationsController
is embed in a Navigation Controller. The objet I want to change is named "label". This is the code:
if let destinationsViewController = storyBoard.instantiateViewControllerWithIdentifier("destinationsID") as? DestinationsViewController {
if let label = destinationsViewController.label{
label.text = "Super!"
}
else{
println("Not good 2")
}
}
else {
println("Not good 1")
}
Unfortunately, I get the message: "Not good 2". This is not good :-(
Thank you.
import UIKit
class DestinationsViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Ok, here's how you can do it. However, if you change the structure of your storyboard then this may break.
First, in DestinationsViewController, you need to set a variable that will hold the text because we're setting the text before the view is rendered. Therefore, the label will not exist yet. When the view loads, it'll set the label.
Now, in the AppDelegate, we set the variable that will set the label when the view loads.
EDIT
After re-reading your last comment, I realized you want to set the label at some point after the app has already been running. You can just move the code in
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
to where you need it. Then you can also set the label directly, because the view has been loaded.