在我的应用程序中,我按下按钮,它会使用 iOS 默认按钮动画更改背景颜色等数字。按钮的默认行为就像 number 只能在区间 [x, x+1] 或 [x-1, x] 中,其中 x 是初始值。但是,如果快速按下按钮,则类似的数字只会迅速增加或迅速减少。
func likeButtonAction(sender:UIButton!) {
var oldValue = sender.titleLabel?.text?.toInt()
println("oldvalue \(oldValue)")
if sender.selected {
//upvote
sender.setTitle(String(oldValue! + 1), forState: UIControlState.Normal|UIControlState.Selected)
println("inc \(oldValue! + 1)")
} else {
//downvote
sender.setTitle(String(oldValue! - 1), forState: UIControlState.Normal|UIControlState.Selected)
println("dec \(oldValue! - 1)")
}
}
EDIT1:当快速按下输出是:
oldvalue Optional(3)
inc 4
oldvalue Optional(4)
dec 3
oldvalue Optional(3)
inc 4
oldvalue Optional(4)
dec 3
oldvalue Optional(4)
inc 5
oldvalue Optional(5)
dec 4
oldvalue Optional(5)
inc 6
oldvalue Optional(6)
dec 5
oldvalue Optional(6)
inc 7
oldvalue Optional(7)
dec 6
oldvalue Optional(7)
inc 8
oldvalue Optional(8)
dec 7
oldvalue Optional(8)
inc 9
oldvalue Optional(9)
dec 8
oldvalue Optional(8)
inc 9
EDIT2:解决方案:这正常工作,但我不知道为什么。解释将不胜感激
func likeButtonAction(sender:UIButton!)
if sender.selected {
//upvote
sender.setTitle(String((sender.titleLabel?.text?.toInt())! + 1), forState: UIControlState.Normal|UIControlState.Selected)
} else {
//downvote
sender.setTitle(String((sender.titleLabel?.text?.toInt())! - 1), forState: UIControlState.Normal|UIControlState.Selected)
}
}