第一次按下时,按钮的UIImage变化不正确

时间:2016-07-28 17:39:35

标签: swift uibutton uiimage

我想在按下时更改按钮的图像。代码如下。问题在于,当您第一次按下按钮时,该部分代码会在" else"之后出现。声明正在执行,视觉上没有任何变化。然后一切正常,第二次和随后的点击。

@IBOutlet weak var beenHereButton: UIButton!

@IBAction func beenHereButtonPressed(sender: AnyObject)
{
    if beenHereButton.imageView!.image == UIImage(named: "locationButton")
    {

        beenHereButton.setImage(UIImage(named: "locationButtonPressed"), forState: .Normal)
        print("Button Pressed")

    }
    else
    {

        beenHereButton.setImage(UIImage(named: "locationButton"), forState: .Normal)
        print("Button released")
    }
}

1 个答案:

答案 0 :(得分:0)

你不应该以这种方式比较图像;看起来像是从storyboard初始化图像,它与UIImage类初始化不完全相同。使用其他解决方案可能你在任何方式都需要代码的其他部分,所以make flag属性:

var buttonPressed = false
@IBOutlet weak var beenHereButton: UIButton!
@IBAction func beenHereButtonPressed(sender: AnyObject)
{
    if !buttonPressed 
    {
        beenHereButton.setImage(UIImage(named: "locationButtonPressed"), forState: .Normal)
        print("Button Pressed")
        buttonPressed = true
    }
    else
    {
        beenHereButton.setImage(UIImage(named: "locationButton"), forState: .Normal)
        print("Button released")
        buttonPressed = false
    }
}