beninabox_uk
beninabox_uk

Reputation: 684

Update Label On Another View

I have two views with a label on one of them. On the second view, there is a button. What I want to achieve here is to be able to press the button and it updates the label on the first view. How do I do that? I can't access the IBOutlet from the second view. Is there something that I have to do to the IBOutlet to make it public etc?

Upvotes: 2

Views: 1764

Answers (2)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

You can use NSNotificationCenter for that.

First of all in your viewDidLoad method add this code in your firstViewController class:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshlbl:", name: "refresh", object: nil)

which will addObserver when your app loads.

And add this helper method in same viewController.

func refreshlbl(notification: NSNotification) {

    lbl.text = "Updated by second View"  //Update your label here.
}

After that in your secondViewController add this code when you dismiss your view:

@IBAction func back(sender: AnyObject) {
    NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: nil, userInfo: nil)
    self.dismissViewControllerAnimated(true, completion: nil)
}

Now when you press back button from secondView then refreshlbl method will call from firstView.

Upvotes: 3

Deepakraj Murugesan
Deepakraj Murugesan

Reputation: 1227

use custom delegate method create a delegate in second view and access that view delegate function in first view. or use NSNotification or use NSUserdefaults

Upvotes: 1

Related Questions