BarButtonItem 未显示

BarButtonItem not showing up

在我制作的应用程序中,我正在尝试启用 login/logout 推特。我想要它以便有一个 barbuttonitem 如果没有当前用户则说登录,或者如果有一个则说注销。我在故事板上创建了两个按钮,一个用于登录,一个用于注销。在 viewDidLoad() 中,我有这个代码:

self.navigationItem.rightBarButtonItem = nil
    self.navigationItem.rightBarButtonItem = nil


    if twitterUser.currentUser != nil {
        print("there is a current user")

        self.navigationItem.rightBarButtonItem = logoutButton

    } else {
        self.navigationItem.rightBarButtonItem = loginButton
    }

它似乎运作良好。当用户实际登录或注销时,问题就来了。这些按钮连接到以下功能:

@IBAction func onLogin(sender: AnyObject) {

    let client = twitterAPI.sharedInstance

    client.login({ () -> () in

        self.navigationItem.rightBarButtonItem =  nil

        self.navigationItem.rightBarButtonItem = self.logoutButton

        }) { (error: NSError) -> () in
            print(error.localizedDescription)
    }


}


    @IBAction func onLogout(sender: AnyObject) {
    twitterAPI.sharedInstance.logout()
    self.navigationItem.rightBarButtonItem = nil
    self.navigationItem.rightBarButtonItem = self.loginButton
}

登录后登录按钮会消失,但注销按钮不会出现。注销时,注销按钮消失但登录按钮不出现。我不确定是什么原因导致的,因为我在 viewDidLoad 中使用了相同的方法并且它似乎工作正常。

此代码可能对您有所帮助

    override func viewDidLoad() 
    {
       super.viewDidLoad()
       barButton = UIBarButtonItem(title: "Login", style: UIBarButtonItemStyle.Done, target: self, action: "barBtnAction:")
       barButton.tag = 0
       self.navigationItem.rightBarButtonItem = barButton
    }

    @IBAction func barBtnAction(sender:UIBarButtonItem)
    {           
       let shouldLogin: Bool = sender.tag == 0 ? true : false
       if shouldLogin
       {
          //your code here
          onLogin()
       }
       else
       {
          //your code here
          onLogout()
       }
    }

  func onLogin()
  {
      barButton.title = "Logout"
      barButton.tag = 1
  }

  func onLogout()
  {
      barButton.title = "Login"
      barButton.tag = 0
  }