注销按钮操作不起作用

Logout button action not working

上下文是,当用户点击登录按钮时,应用程序将使用 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)
    }

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

如果您的 Login 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)



}