简体   繁体   English

按下按钮时更改按钮标题的想法?

[英]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. 使用Swift,我想在点击时更改按钮的标题,例如从“开始”更改为“停止”,反之亦然。 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"? 但是我不明白为什么在“ .setTitle”之前插入了“ sender”而不是“ 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. 插入我的按钮名称以表明我想更改该特定按钮的标题似乎更合乎逻辑。.我距编程仅2周以上,所以我希望你们能用最基本的可理解术语进行解释。 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: 我的问题是关于sender.setTitle(“ Button Title”,forState:UIControlState.Normal)行:

1) What is "sender"? 1)什么是“发件人”? What does it mean? 这是什么意思? Why is it used instead of my button's name? 为什么用它代替我按钮的名称?

2) What is forState? 2)什么是forState? / UIControlState? / 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 . 据我所知, sender就是调用操作的对象,在这种情况下, sender程序就是链接到IBAction BUTTON程序中的BUTTON

More information on UIControlState can be found here . 有关UIControlState的更多信息,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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