BarButtonItem not showing up

匆匆过客 提交于 2019-12-11 14:49:59

问题


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:


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
  }


来源:https://stackoverflow.com/questions/36045541/barbuttonitem-not-showing-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!