swift识别按下了哪个按钮

时间:2018-04-24 06:51:41

标签: ios swift pressed

如何在swift中识别是否按下了哪个按钮我有3个按钮动作。现在我有另一个按钮,当按下它时将识别3按下了哪个按钮。首先,您必须在单击3按钮后单击3按钮,然后单击 识别按下按钮,此按钮将识别或打印按下3中的按钮。

//this button will identify
    @IBAction func idenfifywhichpressed(_ sender: UIButton) {
    }

3个按钮

 @IBAction func btn1(_ sender: UIButton) {
}
 @IBAction func btn2(_ sender: UIButton) {
}
 @IBAction func btn3(_ sender: UIButton) {
}

4 个答案:

答案 0 :(得分:2)

尝试这样的事情

声明枚举

  enum SelectedButtonTag: Int {
     case First
     case Second
     case Third
  }

按钮操作

使用不同的标记

将三个按钮操作连接到此方法
   @IBAction func idenfifywhichpressed(sender: UIButton) {
        switch sender.tag {
        case SelectedButtonTag.First.rawValue:
            print("do something when first button is tapped")
        case SelectedButtonTag.Second.rawValue:
            print("do something when second button is tapped")
        case SelectedButtonTag.Third.rawValue:
            print("do something when third button is tapped")
        default:
            print("default")
        }
    }

答案 1 :(得分:0)

做这样的事,

var index:Int = 0

现在这样做,仅供参考,相应地设置按钮标签1,2和3 ...

@IBAction func btn1(_ sender: UIButton) {
    index = sender.tag
}

@IBAction func btn2(_ sender: UIButton) {
    index = sender.tag
}

@IBAction func btn3(_ sender: UIButton) {
    index = sender.tag
}

现在这个,

@IBAction func idenfifywhichpressed(_ sender: UIButton) {
    if index == 1 {
        //Button 1 Pressed
    }else if index == 2 {
        //Button 2 Pressed
    } else if index == 3{
        //Button 3 Pressed
    }
}

FYI。您也可以在Switch方法中使用idenfifywhichpressed语句。

更新。不要为btn1,btn2和btn3创建三种方法,只需创建一个方法并相应地分配标记即可。

答案 2 :(得分:0)

对@ prajnaranjan-das的小改进回答:立即转换为枚举以清除一些错误并删除在交换机中实现默认的需要......

Variables

答案 3 :(得分:0)

我认为你可以选择像

这样的变量
var checkBtn: String?

在第1个按钮内更改变量值

checkBtn = "1"
第二个按钮内的

更改变量值

checkBtn = "2"

在第3个按钮内更改变量值

checkBtn = "3"

@IBAction func idenfifywhichpressed(_ sender: UIButton) {

    // just print the value of CheckBtn

    print(checkBtn)

    //this will give you which btn pressed right

}
相关问题