当按下太快时,UIButton sender.titleLabel?.text?.toInt()不会提供更新值
在我的应用程序中,我按下了按钮,它使用iOS默认按钮动画更改了backgroundcolor和类似的数字。按钮的默认行为就像数字只能位于区间[x,x + 1]或[x-1,x]中,其中x是初始值。但是,如果按钮被快速按下,相似的数字就会迅速增加或减少。当按下太快时,UIButton sender.titleLabel?.text?.toInt()不会提供更新值
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: SOLUTION: 这个工作正常,但我不知道为什么。解释将不胜感激
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)
}
}
这是行不通的,因为
if sender.backgroundImageForState(UIControlState.Normal) == UIImage(named: "like.png")
永远是假的..
的UIImage(命名为: “like.png”)
将创建新的UIImage实例。
您可以将“标记”分配给任何视图(在本例中为UIButton)来处理这种情况。
我的建议是将按钮状态设置为.Normal和。分别选择为“like.png”和“liked.png”。然后你的代码可以是简单的:
func likeButtonAction(sender:UIButton!) {
if sender.selected {
//upvote
sender.setTitle(String(oldValue! + 1), forState: UIControlState.Normal)
sender.setTitleColor(MyStyle.ThemeSecondColor, forState: UIControlState.Normal)
} else {
//downvote
sender.setTitle(String(oldValue! - 1), forState: UIControlState.Normal)
sender.setTitleColor(MyStyle.ThemeColor, forState: UIControlState.Normal)
}
//Quickly flip the button state to the opposite of what it was
sender.selected = !sender.selected
}
编辑:
嗯,你可以实现一个变量来保存“计数”,并设置第一,然后设置与按钮的值即,不是进出按钮标题的拉动值:
var likeCount:Int = [SET THIS FROM YOUR STORAGE] || 0
func likeButtonAction(sender:UIButton!) {
if sender.selected {
//upvote
likeCount++
println("inc \(likeCount!)")
} else {
//downvote, but do not allow negative values
if likeCount == 0{
likeCount = 0
} else {
likeCount--
}
println("dec \(likeCount!)")
}
sender.setTitle(String(likeCount!), forState: UIControlState.Normal)
sender.selected = !sender.selected
}
这将保持独立价值的跟踪,并从潜在的阻碍了进程保持UI。
谢谢,但它没有奏效。快速按下时,数字仍不准确。 – Thellimist 2015-02-06 15:06:54
我的假设是错误的。问题重新编辑。 – Thellimist 2015-02-06 15:38:15
改变了这种方式,但问题仍然存在。所以我的假设是错误的我会编辑 – Thellimist 2015-02-06 15:18:27