注销按钮操作无效

时间:2017-03-05 09:26:39

标签: ios swift uibutton segue viewcontroller

上下文是,当用户点击登录按钮时,应用程序将使用Web服务检查凭据,如果用户被授权,则用户名和密码存储在userDefaults中(用户再次打开应用程序时自动登录)

现在我正在使用下一页上的注销按钮(成功登录后用户所在的位置),这是我无法正常工作的注销按钮的代码。

据我说,点击退出后,应该删除userDefaults,然后返回登录页面。 目前我并不关心外观,只是帮我代码。

添加按钮的功能。

 override func viewDidLoad()
        {
            super.viewDidLoad()
            let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.trash, target: nil, action: #selector(self.logoutButtonTapped(_:)));
            navigationItem.rightBarButtonItem = doneItem;
            // Do any additional setup after loading the view.
        }

注销按钮的功能:

func logoutButtonTapped(_ sender: Any)
    {
        let defaults = UserDefaults.standard
        defaults.removeObject(forKey: "userName")
        defaults.removeObject(forKey: "userPassword")
        let newViewObject = storyboard?.instantiateViewController(withIdentifier: "LoginPageViewController") as! LoginPageViewController //LoginPageViewController is my login view file, and identifier also has the same name.
        navigationController?.pushViewController(newViewObject, animated: true)
    }

这是我的故事板。我正在以编程方式添加按钮。 enter image description here

1 个答案:

答案 0 :(得分:0)

如果你的登录VC作为初始VC,那么在这个地方打电话

let newViewObject = storyboard?.instantiateViewController(withIdentifier: "LoginPageViewController") as! LoginPageViewController //LoginPageViewController is my login view file, and identifier also has the same name.
    navigationController?.pushViewController(newViewObject, animated: true)

使用

_ = navigationController?.popViewController(animated: true)

其他

  _ = navigationController?.popToRootViewController(animated: true)

更新回答

 func logoutButtonTapped(_ sender: Any)
    {
        let defaults = UserDefaults.standard
        defaults.removeObject(forKey: "userName")
        defaults.removeObject(forKey: "userPassword")
         _ = navigationController?.popToRootViewController(animated: true)

    }

,例如

  navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(logoutButtonTapped))

并调用

之类的操作
 func logoutButtonTapped() {

    let defaults = UserDefaults.standard
    defaults.removeObject(forKey: "userName")
    defaults.removeObject(forKey: "userPassword")

   // _ = navigationController?.popViewController(animated: true)

     _ = navigationController?.popToRootViewController(animated: true)



}