0

Here i have two view controllers and on button click in second view controller i want to change label name in first view controller so how can i do this??

First View Controller where i want to change userName label text

class MenuViewController1: UIViewController,UITableViewDataSource, UITableViewDelegate{

    /**
     *  Array to display menu options
     */
    @IBOutlet var tblMenuOptions : UITableView!

    /**
     *  Transparent button to hide menu
     */
    @IBOutlet var btnCloseMenuOverlay : UIButton!

    /**
     *  Array containing menu options
     */
    var arrayMenuOptions = [Dictionary<String,String>]()

    /**
     *  Menu button which was tapped to display the menu
     */
    var btnMenu : UIButton!

    /**
     *  Delegate of the MenuVC
     */
    var delegate : SlideMenuDelegate?

  //  var delegateP: Profile?

    @IBOutlet weak var userProfilePhoto: UIImageView!

    @IBOutlet weak var userName: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        tblMenuOptions.tableFooterView = UIView()
        // Do any additional setup after loading the view.


        //let name = userName.text
        self.delegateP?.name_changed(name: userName.text!)

         }

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

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        updateArrayMenuOptions()
    }

    func updateArrayMenuOptions(){
        arrayMenuOptions.append(["title":"Home", "icon":"HomeIcon"])
        arrayMenuOptions.append(["title":"LogIn", "icon":"LogIn"])
        arrayMenuOptions.append(["title":"House Owner","icon":"House Owner"])
        arrayMenuOptions.append(["title":"ShortTerm", "icon":"ShortTerm"])
        arrayMenuOptions.append(["title":"LongTerm","icon":"LongTerm"])

        tblMenuOptions.reloadData()
    }

    @IBAction func onCloseMenuClick(_ button:UIButton!){
        btnMenu.tag = 0

        if (self.delegate != nil) {
            var index = Int32(button.tag)
            if(button == self.btnCloseMenuOverlay){
                index = -1
            }
            delegate?.slideMenuItemSelectedAtIndex(index)
        }

        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.view.frame = CGRect(x: -UIScreen.main.bounds.size.width, y: 0, width: UIScreen.main.bounds.size.width,height: UIScreen.main.bounds.size.height)
            self.view.layoutIfNeeded()
            self.view.backgroundColor = UIColor.clear
        }, completion: { (finished) -> Void in
            self.view.removeFromSuperview()
            self.removeFromParentViewController()
        })
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cellMenu")!
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        cell.layoutMargins = UIEdgeInsets.zero
        cell.preservesSuperviewLayoutMargins = false

        cell.backgroundColor = UIColor.clear


        let lblTitle : UILabel = cell.contentView.viewWithTag(101) as! UILabel
        let imgIcon : UIImageView = cell.contentView.viewWithTag(100) as! UIImageView

        imgIcon.image = UIImage(named: arrayMenuOptions[indexPath.row]["icon"]!)
        lblTitle.text = arrayMenuOptions[indexPath.row]["title"]!

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let btn = UIButton(type: UIButtonType.custom)
        btn.tag = indexPath.row
        self.onCloseMenuClick(btn)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrayMenuOptions.count
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1;
    }
}

Second View Controller from where on click of login button want to change label name of First View Controller

class LogInViewController: UIViewController , FBSDKLoginButtonDelegate , GIDSignInUIDelegate{
    @IBOutlet weak var loginButton: UIButton!
    @IBOutlet weak var EnterEmail: UITextField!
    @IBOutlet weak var EnterPassword: UITextField!       

    // Login in button

    @IBAction func loginButtton(_ sender: UIButton) {

        let email = EnterEmail.text?.lowercased()
        let finalEmail = email?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        let password = EnterPassword.text

       // var name: String!
       // menuView = self.storyboard?.instantiateViewController(withIdentifier: "MenuViewController1") as! MenuViewController1

        // Register user in firebase with validations
        Auth.auth().createUser(withEmail: email!, password: password!) { (user, error) in

            if (error == nil && (finalEmail != "") && self.isValidEmail(testStr: finalEmail!)) && (password != " " && self.isPasswordValid(password!)) {
               self.displayMyAlertMessage(userMessage:"You are successfully registered ")                 
            } else {
               self.displayMyAlertMessage(userMessage:"Registration Failed.. Please Try Again !")                    
            }
        };
       // self.navigationController?.pushViewController(MenuViewController1, animated: true)  
    }
}
mugx
  • 9,869
  • 3
  • 43
  • 55

1 Answers1

2

We assume the MenuViewController will be informed that LoginViewController has finished the login. The way is:

First, create a protocol with LoginViewController, and declare a delegate in LoginViewController:

protocol LoginViewControllerDelegate:NSObjectProtocol {
    func LoginDidFinish()
}

class LoginViewController: UIViewController{

    weak var delegate:LoginViewControllerDelegate?
    //......
}

Second, when login is finished, call the delegate method:

Auth.auth().createUser(withEmail: email!, password: password!) { (user, error) in
    if (error == nil && (finalEmail != "") && self.isValidEmail(testStr: finalEmail!)) && (password != " " && self.isPasswordValid(password!)){
        self.displayMyAlertMessage(userMessage:"You are successfully registered ")
        self.delegate?.LoginDidFinish() //Key point
    }else{
        self.displayMyAlertMessage(userMessage:"Registration Failed.. Please Try Again !")
    }
};

Third, in MenuViewController, assign self to be the LoginViewController's delegate when creating LoginViewController:

let loginViewController = LoginViewController()
loginViewController.delegate = self

Finally, implement the delegate method in MenuViewController, and it will be called when login is done:

//MARK: - LoginViewControllerDelegate
func LoginDidFinish() {
    print("Login did finish")
    //And change your label's text here.
}
Yun CHEN
  • 6,450
  • 3
  • 30
  • 33
  • Thank you Yun Chen but it is still not printing login did finish wrote in loginDidFinish() function.. – Rutuja Pawal Oct 14 '17 at 04:30
  • Make a breakpoint on `self.delegate?.LoginDidFinish()` to check if it's being called. And make sure `self.delegate` is not nil by the way. – Yun CHEN Oct 14 '17 at 04:36
  • Yup u r right.. self.delegate?.LoginDidFinish() here is problem. sender UIButton 0x00007f962a55aaa0 self DivaStays.LogInViewController 0x00007f962a455510 email String? "pooja@gmail.com" some finalEmail String? "pooja@gmail.com" some password String? "pooja@45ff" some got this at breakpoint – Rutuja Pawal Oct 14 '17 at 04:58
  • Sorry, I don't understand your description. – Yun CHEN Oct 14 '17 at 07:31