Image in a UIButton

Hello!!!


I need to change the Image of a UIButton when user taps it.


How can I do that?


I tried that:


if let image = UIImage(named: "image.png") {

cmdClock.setImage(image, forState: .Normal)

}


But XCode shows this message:


'(UIButton) -> ()' does not have a member name setImage


Thanks!!!

How do you declare your `cmdClock`?

A simple code like this shows the same error message:

    @IBAction func cmdClock(sender: UIButton) {
        if let image  = UIImage(named: "image.png") {
            cmdClock.setImage(image, forState: .Normal)
        }
    }

In this case, the cause of the error is obvious, cmdClock is a method name, not representing UIButton.

Fixed code would be:

    @IBAction func cmdClock(sender: UIButton) {
        if let image  = UIImage(named: "image.png") {
            sender.setImage(image, forState: .Normal)
        }
    }


If you are struggling with more complex problem, you need to show more details.

Hello


Try it

@IBAction func btnTest(sender: UIButton) {
       
            if let image = UIImage(named:"img1") {
                sender.setImage(image, forState: .Normal)
            }
            if let image = UIImage(named:"img2") {
                sender.setImage(image, forState: .Normal)
            }
            
    }
Image in a UIButton
 
 
Q