Search code examples
iosswiftuilabel

change label from another viewcontroller on swift


I want to change label from another viewController.

First viewcontroller is MenuController. Second one is LoginViewController.

I want to change MenuController's Label.text from LoginViewController.

In LoginViewController:

let viewController = MenuController()
viewController.changeLabel("logout")

In MenuController:

class MenuController: UITableViewController {
    var attractionImages = [String]()
    var attractionNames = [String]()
    var webAddresses = [String]()

    @IBOutlet weak var loginLabel: UILabel!


    override func viewDidLoad() {
        super.viewDidLoad()

        loginLabel.text = "Login"
        print(loginLabel.text)

    }

    func changeLabel(Log: String)O {
        self.loginLabel.text = log
        print (log)
    }

But an error occur.

fatal error: unexpectedly found nil while unwrapping an Optional value

How can I solve it?

Thanks for your help.


Solution

  • 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.