Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set image of UIButton in Swift 3?

Originally, my code was working.

IBAction func clickedon(_ sender: UIButton) {

    if(gamestate[sender.tag] == 0 && gameisactive == true){

        gamestate[sender.tag] = activeplayer

    if (activeplayer == 1){
        print("working")
        sender.setImage(UIImage(named:"Cross.png"), for: UIControlState()) <-----------
        activeplayer = 2
    }
    else {
        print("working2")
        sender.setImage(UIImage(named:"Nought.png"), for: UIControlState()) <-----------
        activeplayer = 1

    } 
    }

These two pieces of code that set image were working. These buttons have nothing set to their image. When they are clicked on, I want them to switch to those images. Those images are in the folder with the view controller. I am not sure why they stopped working. I commented out all other code to see if it could be an issue but it doesn't seem to be. The print statements get printed out in both cases. It's just the set image that doesn't seem to do anything. There is no error, it just does nothing.

I don't really understand the UIControlState() code. I am mimicking an online project that has the same code and it works. It is really strange. Please let me know if you have any suggestions!

like image 468
Aditya Yadav Avatar asked Feb 05 '23 20:02

Aditya Yadav


2 Answers

IBAction func clickedon(_ sender: UIButton) {

if(gamestate[sender.tag] == 0 && gameisactive == true){

    gamestate[sender.tag] = activeplayer

if (activeplayer == 1){
    print("working")
   sender.setImage(UIImage(named: "Cross.png")!, forState: UIControlState.Normal)
   sender.setImage(UIImage(named:"CrossSelected.png")!, forState: UIControlState.Selected)

    activeplayer = 2
}
else {
    print("working2")
    sender.setImage(UIImage(named: "Nought.png")!, forState: UIControlState.Normal)
    sender.setImage(UIImage(named:"NoughtSelected.png")!, forState: UIControlState.Selected)
    activeplayer = 1

} 
}
like image 97
Himali Shah Avatar answered Feb 19 '23 04:02

Himali Shah


You can try this :

let image = UIImage(named: "imagename.png")
yourButton.setBackgroundImage(image, for: .normal)

I try using other setImage calls but not working. I found this setBackgroundImage to let the image appear. Hope that it will helps you.

like image 41
Syafiq Sinwan Avatar answered Feb 19 '23 04:02

Syafiq Sinwan