【发布时间】:2016-03-11 04:24:07
【问题描述】:
我有一个如图所示的按钮,当用户首先按下它时,它应该会更改图像并且用户现在正在关注此配置文件。但是,当用户第一次按下按钮时,它什么也不做,第二次点击它就可以工作。如何在第一次点击时完成这项工作?
编辑清理后的代码此代码需要点击两次按钮才能工作。双击它会跟随或取消关注用户并更新图像。但就像我说的那样,它需要点击两次。
@IBAction func favButton(sender: UIButton) {
buttonPressed = !buttonPressed
if buttonPressed == true {
let followedObjectId = userToShowDetail?["name"] as? String
if isFollowing[followedObjectId!] == true {
}
} else {
let followedObjectId = userToShowDetail?["name"] as? String
if isFollowing[followedObjectId!] == false {
isFollowing[followedObjectId!] = true
sender.setImage(UIImage(named: "fave_on@2x.png"), forState: UIControlState.Normal)
print("follow")
let following = PFObject(className: "Followers")
following["following"] = userToShowDetail?["name"] as? String
following["follower"] = PFUser.currentUser()?.objectId
favLabel.text = "Favourite Jammer"
following.saveInBackground()
} else {
if buttonPressed != true {
isFollowing[followedObjectId!] = false
print("notFollow")
sender.setImage(UIImage(named: "fave_off@2x.png"), forState: UIControlState.Normal)
favLabel.text = "Add to favourites?"
}
}
}
此代码在视觉上修复了它,但它不再在幕后工作。 按钮更改图像并打印关注和取消关注日志,但它不会取消关注用户并添加关注用户访问我的数据两次。
buttonPressed = !buttonPressed
if buttonPressed == true {
let followedObjectId = userToShowDetail?["name"] as? String
isFollowing[followedObjectId!] = true
sender.setImage(UIImage(named: "fave_on@2x.png"), forState: UIControlState.Normal)
print("follow")
let following = PFObject(className: "Followers")
following["following"] = userToShowDetail?["name"] as? String
following["follower"] = PFUser.currentUser()?.objectId
favLabel.text = "Favourite Jammer"
following.saveInBackground()
} else {
if buttonPressed != true {
let followedObjectId = userToShowDetail?["name"] as? String
isFollowing[followedObjectId!] = false
print("notFollow")
sender.setImage(UIImage(named: "fave_off@2x.png"), forState: UIControlState.Normal)
favLabel.text = "Add to favourites?"
} // !=true
} // else
} // uibutton
【问题讨论】:
-
代码有点乱... 初始查询应该在
ViewDidLoad中,以便在按下按钮之前值就在那里。然后按下按钮时的其余逻辑也需要在一个单独的函数中并分解为多个部分。该按钮发生了太多事情。 -
当您将按钮链接到您的类时(ctrl + 从界面构建器拖动到视图控制器),您是否从按钮内部进行了润色(ctrl + 单击按钮并告诉我是否连接在里面
-
Kholl ya 它在里面修饰。 @likeslvi 好的,我试着清理一下她,看看是否会有所改善。
-
我正在写一个答案来帮助您改进代码。但是图像更改应该发生在按钮内,而其他一切(查询、更改数据等)需要在函数内和 viewDidLoad 内发生。一旦这样,您就可以轻松更改图像。
-
好的,非常感谢@lukeslvi
标签: ios swift button uibutton swift2