Search code examples
swiftuibuttonxcode6

UIButton setTitle doesn't work


I'm trying to change the text of a UIButton when it gets clicked. I've tried the following things, which failed:

First I tried inserting a button on the storyboard and linking it to the view controller, with the code for the button appearing like this:

@IBAction func button(sender: AnyObject) {}. 

Within the button's parentheses, I then used

button.setTitle ("something" , for State: .Selected)

However, when I run this code in the simulator, it doesn't seem to work at all.

I have also tried, following the Apple reference manual, to set different labels for different states in the side menu after clicking on said button, but still this didn't work. Can anyone tell me exactly (i.e. what code to write and where exactly it goes) how to make this happen?


Solution

  • The type of the sender should be UIButton, when creating the IBAction function. The sender is your button. The function is called when you tap on the button. You must use the function setTitle on the sender(your button).

    @IBAction func buttonTouchedUpInside(sender: UIButton) { 
        sender.setTitle("buttonName", forState: .normal)
    }