var amtOfLikes = 0
@IBAction func whenPressed (sender:UIButton, forEvent event: UIEvent){
likesLbl.text = "Likes \(amtOfLikes+1)"
likeBtn.setTitle("- Like", forState: UIControlState.Normal)
}
我们的问题是我们要确保如果LIKEBTN的标签是" + Like",则amtOfLikes + 1并将LIKEBTN更改为" - Like"。然后另一个IF LIKEBTN是" -Like"在这种情况下,这是不可避免的,因为它已被改变,然后amtOfLikes-1。它相当简单,但我们不确定如何编写代码。
答案 0 :(得分:0)
首先保持数据状态:
var liked: Bool = false
在点击处理程序中,您只需更改其值:
@IBAction func whenPressed(sender: UIButton, forEvent event: UIEvent) {
self.liked = !self.liked
}
您实际上可以在didSet
回调中实现代码:
var liked: Bool = false {
didSet {
let title = liked ? "- Like" : "+ Like"
likeBtn.setTitle(title, forState: UIControlState.Normal)
}
}
或者您可以将其拆分为多个功能:
var liked: Bool = false {
didSet {
updateUIState()
}
}
private func updateUIState() {
let title = liked ? "- Like" : "+ Like"
likeBtn.setTitle(title, forState: UIControlState.Normal)
}
更改amtOfLikes
应该是相同的。不要直接更改UI。更改您的模型,然后根据您的模型更新您的UI。