Swift如何在以前的视图控制器

时间:2016-05-05 01:16:07

标签: ios swift

我想在AccountViewController中按下后退按钮时,从我的AccountViewController更新DashboardViewController中的标签。

我尝试将变量从第二个视图传回第一个视图并更新viewDidLoad和viewWillAppear中的标签,但是当第一个视图返回到屏幕时它永远不会更新标签。

我尝试在第一个视图中创建一个函数,用一个传递给函数的字符串来更新标签,并从第二个视图调用该函数,但是它表示标签为零,因此无法更新。

我最近的尝试是创建一个委托,但这也不起作用。

这是我的代表尝试。

 class DashboardViewController: UIViewController, AccountViewControllerDelegate {
 @IBOutlet weak var welcome_lbl: UILabel!

    func nameChanged(name: String){
    var full_name = "Welcome \(name)"
    welcome_lbl.text = "\(full_name)"
}
    override func viewDidLoad() {
    super.viewDidLoad()

    AccountViewController.delegate = self
}
}

然后在我的AccountViewController中我有了这个

protocol AccountViewControllerDelegate{
func name_changed(name: String)
}

class AccountViewController: UIViewController, UITextFieldDelegate {
   var info_changed = false
static var delegate: AccountViewControllerDelegate!
    @IBAction func back_btn(sender: AnyObject) {
    if(info_changed){
        AccountViewController.delegate.name_changed(name_tf.text!)
    }
    self.dismissViewControllerAnimated(true, completion: nil)
}

我是否以某种方式弄乱了委托流程?或者有更简单的方法吗?

1 个答案:

答案 0 :(得分:1)

首先。您的委托应该是AccountViewController的普通属性。用户按下后无需更新您的姓名。当AccountViewController中的用户更改名称时,您可以更改DashboardViewController的名称。当用户返回DashboardViewController时。它已经显示更改的名称。

protocol AccountViewControllerDelegate{
    func name_changed(name: String)
}

class AccountViewController: UIViewController, UITextFieldDelegate {

  var delegate: AccountViewControllerDelegate?

    // when user change name through textfield or other control
    func changeName(name: String) {
        delegate?.name_changed(name)
    }

}

二。当DashboardViewController显示AccountViewController时。我认为应该推动。将DashboardViewController实例设置为AccountViewController实例的委托。

class DashboardViewController: UIViewController, AccountViewControllerDelegate {
    @IBOutlet weak var welcome_lbl: UILabel!

    func nameChanged(name: String){
    var full_name = "Welcome \(name)"
    welcome_lbl.text = "\(full_name)"
    }

    // present or push to AccountViewController
    func showAccountViewController {
        let accountViewController = AccountViewController()
        accountViewController.delegate = self
        // do push view controller
    }
}