ios - 如何创建委托(delegate)以在单击另一个 View Controller 的按钮时更改一个 View Controller 中的标签名称

标签 ios swift

这里我有两个 View Controller ,在第二个 View Controller 中单击按钮我想更改第一个 View Controller 中的标签名称,我该怎么做?

我想更改用户名标签文本的第一个 View Controller

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;
    }
}

第二个 View Controller 从哪里点击登录按钮想要更改第一个 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)  
    }
}

最佳答案

我们假设 MenuViewController将被告知LoginViewController已完成登录。方法是:

首先,用LoginViewController 创建一个协议(protocol) , 并在 LoginViewController 中声明一个委托(delegate) :

protocol LoginViewControllerDelegate:NSObjectProtocol {
    func LoginDidFinish()
}

class LoginViewController: UIViewController{

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

其次,登录完成后,调用委托(delegate)方法:

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 !")
    }
};

第三,在MenuViewController , 分配 self成为LoginViewController创建 LoginViewController 时的 delegate :

let loginViewController = LoginViewController()
loginViewController.delegate = self

最后,实现MenuViewController中的委托(delegate)方法 , 登录完成后会被调用:

//MARK: - LoginViewControllerDelegate
func LoginDidFinish() {
    print("Login did finish")
    //And change your label's text here.
}

关于ios - 如何创建委托(delegate)以在单击另一个 View Controller 的按钮时更改一个 View Controller 中的标签名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46724688/

相关文章:

arrays - UITableView 中的 UICollectionView - 我想在 CollectionVewCell 中显示数据

objective-c - UILabels 使我的应用程序崩溃

ios - Firebase 嵌套索引查询规则

ios - 关闭 View Controller 后约束崩溃

ios - 尝试与 Azure 移动服务同步时出现 IMobileServiceClient.PullAsync 死锁

ios - 获取错误线程 1 : EXC_BAD_ACCESS (code=EXC_I386_GPFLT) when loading AVPlayer

swift - 在 Swift 3 和 Xcode 8 中从嵌套字典中获取值的问题

ios - Spritekit制作的游戏在真机上第一次玩声音很低?

iphone - 无法在 iPhone 上测试应用程序

ios - Xcode - 如何修复 'NSUnknownKeyException' ,原因 : … this class is not key value coding-compliant for the key X"error?