A. Bhakta
A. Bhakta

Reputation: 33

How to change outlet properties from global scope?

I need a function from global scope change a label on the storyboard.

When I try running this code, the error I get is:

fatal error: unexpectedly found nil while unwrapping an Optional value

The problem is that viewController.congratulations is null.

How to fix that? Thanks in advance!

func myAlert ()
{
    // how to change 'configuration.text' from here?

    let storyboard = UIStoryboard(name: "Main", bundle: nil);
    let viewController : ViewController = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController;

    viewController.congratulations.text = "test";
}

class ViewController: UIViewController
{
    @IBOutlet weak var congratulations: UILabel!;

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

        myAlert();
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Upvotes: 0

Views: 119

Answers (3)

A. Bhakta
A. Bhakta

Reputation: 33

Adding myAlert() into ViewController class solved the problem.

class ViewController: UIViewController
{
    func myAlert ()
    {
        self.congratulations.text = "vrebreberbfrbb";
    }

    @IBOutlet weak var congratulations: UILabel!;

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

        myAlert();
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Upvotes: 0

pkc
pkc

Reputation: 8512

The IBOutlet named congratulations is nil in viewDidLoad. So make a String property at ViewController (say stringValue). Set that string property while navigation

In your viewController's viewDidLoad method, get the stringValue and set its value to label

self.congratulations.text = stringValue;

Upvotes: 0

David Pasztor
David Pasztor

Reputation: 54716

You shouldn't directly try to access a UILabel from outside the class where it is defined. Labels are only created once viewDidLoad is called on the specific instance of your UIViewController subclass.

What you should do is store the text you want to display on your label in another variable and change that variable from outside your class.

Upvotes: 1

Related Questions