簡體   English   中英

快速識別按下了哪個按鈕

[英]swift identify which button was pressed

如何快速識別是否按下了哪個按鈕我有 3 個按鈕操作。現在我有另一個按鈕,當按下它時它將識別按下 3 個按鈕中的哪個按鈕。 原因首先是您必須在單擊 3 按鈕后單擊 3 按鈕,然后您將單擊 identfifywhichpressed 按鈕,此按鈕將識別或打印 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) {
}

嘗試這樣的事情

聲明一個枚舉

  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")
        }
    }

做這樣的事情,

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
    }
}

供參考。 您也可以在idenfifywhichpressed方法中使用Switch語句。

更新。 不要為 btn1、btn2 和 btn3 創建三個方法,為簡單起見,只需創建一個方法並相應地分配標簽。

@prajnaranjan-das 答案的小改進:立即轉換為枚舉以清理一些雜物並消除在開關中實現默認值的需要......

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

func buttonTapped(_ sender: UIButton) {
    guard let knownSender = ButtonTag(rawValue: sender.tag) else { return }
    switch knownSender {
    case .First:
        print("do something when first button is tapped")
    case .Second:
        print("do something when second button is tapped")
    case .Third:
        print("do something when third button is tapped")
    }
}

我認為您可以采用類似的變量

var checkBtn: String?

在第一個按鈕內更改變量值

checkBtn = "1"

在第二個按鈕內更改變量值

checkBtn = "2"

在第三個按鈕內更改變量值

checkBtn = "3"

@IBAction func idenfifywhichpressed(_ sender: UIButton) {

    // just print the value of CheckBtn

    print(checkBtn)

    //this will give you which btn pressed right

}

這對我有幫助(swift 5.0)

@IBAction func hardnessSelected(_ sender: UIButton) {
        print(sender.currentTitle) // <----------
    }
    

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM