2017-03-05 68 views
-1

的背景下,当用户点击登录按钮,应用程序将检查与网络服务的凭据,如果用户被授权的用户名和密码存储在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

+0

你能证明你的stroyboard场景 –

+0

了'target'设置为'self' –

回答

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) 



} 
+0

的动作看此例如HTTPS ://makeapppie.com/tag/uinavigationcontroller-in-swift/ –

+0

肯定,我会看到,我也来试试这个答案。谢谢。 :) 我也更新了我的问题与故事板图像。 –

+0

你可以在你登录按钮动作 –