Bon K
Bon K

Reputation: 95

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.

Upvotes: 6

Views: 8838

Answers (2)

balazs630
balazs630

Reputation: 3692

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.

Upvotes: 5

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

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.

Upvotes: 15

Related Questions