change label from another viewcontroller on swift

Another way to achieve that is you can use NSNotificationCenter. Blow is the example for that:

In your MenuController add this code:

override func viewDidLoad() {
    super.viewDidLoad()
     NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshLbl:", name: "refresh", object: nil)
}

Also add this helper method:

func refreshLbl(notification: NSNotification) {

    print("Received Notification")
    lbl.text = "LogOut"
}

Now in your LoginViewController your back button action will look like:

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

Now when ever you press back button from LoginViewController your refreshLbl method will call from MenuController.

For more info refer THIS example.


Swift 3 version:

In your MenuController (where the label needs to be changed) add this code:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, 
                                           selector: #selector(refreshLbl),
                                           name: NSNotification.Name(rawValue: "refresh"),
                                           object: nil)
}

Also add this helper method:

@objc func refreshLbl() {
    print("Received Notification")
    lbl.text = "LogOut"
}

Now in your LoginViewController your back button action will look like:

@IBAction func backButton(_ sender: Any) {
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refresh"), object: nil)
    // Any additional code...
}

Now when ever you press back button from LoginViewController your refreshLbl() method will call from MenuController.

Tags:

Ios

Uilabel

Swift