在我正在制作的应用程序中,我尝试启用登录/注销到Twitter。我想要它,以便有一个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中使用相同的方法,它似乎工作正常。
答案 0 :(得分:1)
此代码可以帮助您
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
}