Alex Marchant
Alex Marchant

Reputation: 670

Setting a buttons image using another button - Swift

I am trying to change a buttons image using another button. The idea being this button resets the buttons to their original state to allow the user to play again.

@IBAction func playAgainButton(_ sender: Any) {
    grid = ["0", "3", "4", "5", "6", "7", "8", "9", "a"]
    let btnCheckMarkImage = UIImage(cgImage: "Image-1" as! CGImage)
    gridSpace0.setImage(btnCheckMarkImage, forState: UIControlState.Normal)
    gameResultLabel.isHidden = true
    //let image = UIImage(named: "blankSpace")
}

@IBAction func gridSpace0(_ sender: Any) {
    let button = sender as! UIButton
    checkIfFree(gridSpace: 0, sender: button)
}

func checkIfFree(gridSpace: Int, sender: UIButton) {
    if(player % 2 != 0)
    {
        player = playerone
        currentPlayerName = playerOneName
    }
    else
    {
        player = playertwo
        currentPlayerName = playerTwoName
    }
    if(grid[gridSpace] != "1" && grid[gridSpace] != "2")
    {
        if(player == playerone)
        {
            let image = UIImage(named: "TicTacToeX")
            grid[gridSpace] = String(player)
            sender.setBackgroundImage(image, for: UIControlState.normal)
            player = player + 1;
        }
        else
        {
            let image = UIImage(named: "TicTacToeO")
            grid[gridSpace] = String(player)
            sender.setBackgroundImage(image, for: UIControlState.normal)
            player = player + 1;
        }

So each time a button is pressed by the user, the space is checked to see if it is free, if so it changes the image of the button.

Like I said, I want the play again button to change the image of gridSpace0 button but when I use the code above I get this error:enter image description here

I need to user the sender part for the button to identify which button is being pressed, so how can I change it's background?

Thanks

Upvotes: 0

Views: 237

Answers (1)

Fangming
Fangming

Reputation: 25260

Your gridSpace0 is a function so you cannot set image like that.

@IBAction func gridSpace0(_ sender: Any) {
    let button = sender as! UIButton
    checkIfFree(gridSpace: 0, sender: button)
}

You need to first link your button to your view controller, and then set button like this enter image description here

Upvotes: 3

Related Questions