Swift中的多个连接 - 如何确定按下了哪个按钮? [重复]

时间:2021-08-25 11:42:47

This question already has an answer here:

这个问题在这里已有答案:

I have four buttons all with the same connection to a single function within the code, and I can't figure out how to determine which button sent the request. ~_~

我有四个按钮都与代码中的单个函数具有相同的连接,我无法弄清楚如何确定哪个按钮发送了请求。 〜_〜

4 个解决方案

#1


You could set each UIButton's tag to "1" "2" "3" "4"

您可以将每个UIButton的标记设置为“1”“2”“3”“4”

func buttonPressed(sender: AnyObject) {
    if sender.tag == 1 {
        //Code for button1
    } else if sender.tag == 2 {
        //Code for button2
    } else if sender.tag == 3 {
        //Code for button3
    } else if sender.tag == 4 {
        //Code for button1
    }
}

#2


You can simply check the title of the button pressed for instance with button.currentTitle

您只需使用button.currentTitle检查按下的按钮的标题即可

If all buttons have the same one, you can check its restoration id

如果所有按钮都具有相同的按钮,则可以检查其恢复ID

#3


As a 3rd alternative (now) you can use the tag property and simply number the single buttons.

作为第三种选择(现在),您可以使用tag属性并简单地对单个按钮进行编号。

func buttonPressed(sender: AnyObject) -> () {
    if let button = sender as? UIButton {
        switch (button.tag){
        case 1:
        //code
        case 2:
        //code
        case 3:
        //code
        case 4:
        //code
        }
    }
}

#4


func buttonPressed(sender: AnyObject) -> () {
    if let button = sender as? UIButton {
        println("\(button.currentTitle)")
    } else {
        println("sender is not a UIButton!")
    }
}

#1


You could set each UIButton's tag to "1" "2" "3" "4"

您可以将每个UIButton的标记设置为“1”“2”“3”“4”

func buttonPressed(sender: AnyObject) {
    if sender.tag == 1 {
        //Code for button1
    } else if sender.tag == 2 {
        //Code for button2
    } else if sender.tag == 3 {
        //Code for button3
    } else if sender.tag == 4 {
        //Code for button1
    }
}

#2


You can simply check the title of the button pressed for instance with button.currentTitle

您只需使用button.currentTitle检查按下的按钮的标题即可

If all buttons have the same one, you can check its restoration id

如果所有按钮都具有相同的按钮,则可以检查其恢复ID

#3


As a 3rd alternative (now) you can use the tag property and simply number the single buttons.

作为第三种选择(现在),您可以使用tag属性并简单地对单个按钮进行编号。

func buttonPressed(sender: AnyObject) -> () {
    if let button = sender as? UIButton {
        switch (button.tag){
        case 1:
        //code
        case 2:
        //code
        case 3:
        //code
        case 4:
        //code
        }
    }
}

#4


func buttonPressed(sender: AnyObject) -> () {
    if let button = sender as? UIButton {
        println("\(button.currentTitle)")
    } else {
        println("sender is not a UIButton!")
    }
}