keatwei
keatwei

Reputation: 257

How to change its own button image on tap in Swift

Now i have an button with an image, I wanted to change the button image when I tap the button. How to change its own button image on tap in Swift

do i need to add an outlet?

@IBOutlet weak var btnSmiley: UIButton!

@IBAction func btnSmiley(sender: AnyObject) {
    btnSmiley.image = UIImage(named: "smiley")
}

Upvotes: 4

Views: 6385

Answers (3)

John Corder
John Corder

Reputation: 151

Swift 5

    var check = true

    @IBOutlet weak var btnSmiley: UIButton!

    @IBAction func btnSmiley(sender: AnyObject) {

        check = !check

        if check == true {
            btnSmiley.setImage(UIImage(named: "red"), for: .normal)
        } else {
            btnSmiley.setImage(UIImage(named: "blue"), for: .normal)
        }
    }

Upvotes: 2

Ar Aui
Ar Aui

Reputation: 392

I use this

@IBAction func btnSmiley(sender: AnyObject) {
    btnSmiley .setImage(image, forState: .Normal)
}

Upvotes: 0

mustafa
mustafa

Reputation: 15464

Do it like this

@IBAction func btnSmiley(sender: UIButton) {
    if let image = UIImage(named:"smiley") {
        sender.setImage(image, forControlState: .Normal)
    }
}

Upvotes: 4

Related Questions