BarButtonItem not showing up

2019-07-27 01:50发布

In an app Im making, Im trying to enable login/logout to twitter. I want it so that there is a barbuttonitem that either says login if there is no current user, or logout if there is one. I created two buttons on the storyboard, one for login and one for logout. In the viewDidLoad(), I have this code:

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
    }

and it seems to work well. The problem comes when the user actually logs in or out. The buttons are connected to the following functions:

@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
}

After logging in the login button will disappear, but the logout button does not show up. When logging out, the logout button disappears but the login button does not appear. I'm not sure what would be causing this, as I use the same methods in the viewDidLoad and it seems to work fine.

1条回答
▲ chillily
2楼-- · 2019-07-27 02:19

This code may help you

    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
  }
查看更多
登录 后发表回答