简体   繁体   中英

The idea of changing a button's title when pressed?

Using Swift, I wanted to change a button's title when tapped, for eg 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?

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM