所以我有一个带有 3 个按钮的情节提要
有没有办法为每个按钮获取某种标识符?
顺便说一句,它们是图像,所以它们没有标题.
@IBAction func mainButton(sender: UIButton) {打印(发件人)}
您可以在情节提要中为每个按钮设置一个 tag
.然后你可以这样识别它们:
@IBAction func mainButton(sender: UIButton) {println(sender.tag)}
为了提高可读性,您可以定义一个枚举,其值对应于所选标签.因此,如果您为按钮设置 0
、1
、2
等标签,则可以在类声明上方执行以下操作:
枚举 SelectedButtonTag: Int {案例一案例二案例三}
然后您将拥有以下内容,而不是处理硬编码的值:
@IBAction func mainButton(sender: UIButton) {切换发件人.tag {案例 SelectedButtonTag.First.rawValue:println("当第一个按钮被点击时做一些事情")案例 SelectedButtonTag.Second.rawValue:println("当第二个按钮被点击时做一些事情")案例 SelectedButtonTag.Third.rawValue:println("当第三个按钮被点击时做某事")默认:println("默认")}}
So I have a storyboard with 3 buttons I want to just create 1 action for all those 3 buttons and decide what to do based on their label/id...
Is there a way to get some kind of identifier for each button?
By the way they are images, so they don't have a title.
@IBAction func mainButton(sender: UIButton) {
println(sender)
}
You can set a tag
in the storyboard for each of the buttons. Then you can identify them this way:
@IBAction func mainButton(sender: UIButton) {
println(sender.tag)
}
EDIT: For more readability you can define an enum with values that correspond to the selected tag. So if you set tags like 0
, 1
, 2
for your buttons, above your class declaration you can do something like this:
enum SelectedButtonTag: Int {
case First
case Second
case Third
}
And then instead of handling hardcoded values you will have:
@IBAction func mainButton(sender: UIButton) {
switch sender.tag {
case SelectedButtonTag.First.rawValue:
println("do something when first button is tapped")
case SelectedButtonTag.Second.rawValue:
println("do something when second button is tapped")
case SelectedButtonTag.Third.rawValue:
println("do something when third button is tapped")
default:
println("default")
}
}
这篇关于通过发件人在 Swift 上获取按钮按下的 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!