How to install a UIButton image in Swift 3?

My code originally worked.

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 installed the image worked. These buttons have nothing to do with their image. When they are clicked, I want them to switch to these images. These images are located in the folder with the view controller. I do not know why they stopped working. I commented on all the other code to find out if this might be a problem, but it doesn't seem to be. Print operations print in both cases. This is just a given image that does not seem to do anything. No mistake, she just does nothing.

UIControlState(). -, , . . , , !

+4
6

IBAction func clickedon (_ : 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

} 
}
+4

:

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

setImage, . setBackgroundImage, . , .

+3

UIControlState() UIControlState.normal UIControlState.highlighted.

https://developer.apple.com/reference/uikit/uicontrolstate

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.normal)
        sender.setImage(UIImage(named:"Cross_highlighted.png"), for: UIControlState.highlighted)
        activeplayer = 2
    }
    else {
        print("working2")
        sender.setImage(UIImage(named:"Nought.png"), for: UIControlState.normal)
        sender.setImage(UIImage(named:"Nought_highlighted.png"), for: UIControlState.highlighted)
        activeplayer = 1

    } 
}
+1

? , . , ; .

  UIImage(named:"Cross.png")!
  sender.setImage(image, for: .normal)
  sender.frame.size = image.size
0

. UIControlState.normal , , . , , .

, . !

0
self.button.setImage(UIImage(named: "namebutton"), for: .normal)

swift 3, , , .

0

Source: https://habr.com/ru/post/1659132/


All Articles