Reputation: 1144
Using Swift, I wanted to change a button's title when tapped, for e.g. from "Start" to "Stop" and vice versa. This is what I did:
var runningcode = false
@IBAction func BUTTON(sender: UIButton) {
if runningcode {
runningcode = false
sender.setTitle("Start", forState: UIControlState.Normal)
} else {
runningcode = true
sender.setTitle("Stop", forState: UIControlState.Normal)
}
}
This worked. But I don't understand why "sender" is inserted before .setTitle instead of "BUTTON"? It seems more logical to insert my button's name to indicate I want to change that specific button's title.. I'm just 2 weeks+ into programming so I hope you guys could explain in the most basic understandable terms ya. Or if anyone could direct me to a book/site/author for basic learning I would really appreciate it.
My question is regarding the sender.setTitle("Button Title", forState: UIControlState.Normal) line:
1) What is "sender"? What does it mean? Why is it used instead of my button's name?
2) What is forState? / UIControlState? Why is it Normal? What does it mean?
Upvotes: 0
Views: 1199
Reputation: 104
As far as I am aware, sender
is just whatever is invoking the action and in this case is the button in your program linked to the IBAction BUTTON
.
More information on UIControlState can be found here.
Upvotes: 2
Reputation: 9397
Use button states, and set a different title for a normal state, and a highlighted state:
sender.setTitle("Unpressed", forState: UIControlState.Normal)
sender.setTitle("Pressed", forState: UIControlState.Highlighted)
If you want the title change to persist, use the selected state of the button rather than highlighted.
sender.setTitle("Selected", forState: UIControlState.Selected)
//Inside your button callback
sender.selected = !sender.selected
When your finger is over the button, it is in the highlighted state. You need to set this up at the time of creating your button. No need to add this code to the button pressed callback.
Upvotes: 2