2017-03-05 36 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

你可以在你登錄按鈕動作 –