Get button pressed id on Swift via sender

后端 未结 15 1092
广开言路
广开言路 2020-12-01 04:21

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 s

相关标签:
15条回答
  • 2020-12-01 05:15

    In my case what i did, just like the answers above i used the tag to identify the specific button, what i added is that i added a UIButton extension that adds an id so that i can set a string id

    i had three buttons with tags 0, 1 and 2

    Then created the extension

    extension UIButton {
        var id: String {
            let tag = self.tag
    
            switch tag {
                case 0:
                    return "breakfast"
    
               case 1:
                   return "lunch"
    
               case 2:
                   return "dinner"
    
               default:
    
                   return "None"
           }
        }
      }
    

    When accessing a button in an IBAction i would just call:

    sender.id
    
    0 讨论(0)
  • 2020-12-01 05:16

    Assuming you gave them all proper names as @IBOutlets:

    @IBOutlet var weak buttonOne: UIButton!
    @IBOutlet var weak buttonTwo: UIButton!
    @IBOutlet var weak buttonThree: UIButton!
    

    You can use the following to determine which is which

    @IBAction func didPressButton(sender: AnyObject){
     // no harm in doing some sort of checking on the sender
     if(sender.isKindOfClass(UIButton)){
    
        switch(sender){
        case buttonOne:    
                       //buttonOne action  
                       break
        case buttonTwo:   
                      //buttonTwo action  
                       break
        case buttonThree: 
                      //buttonThree action  
                       break
        default:
                       break
        }
    }
    
    0 讨论(0)
  • 2020-12-01 05:18

    If you want to create 3 buttons with single method then you can do this by following code...Try this

    Swift 3
    Example :-

    override func viewDidLoad()
    {
        super.viewDidLoad()
        Button1.tag=1
        Button1.addTarget(self,action:#selector(buttonClicked),
                          for:.touchUpInside)
        Button2.tag=2
        Button2.addTarget(self,action:#selector(buttonClicked),
                          for:.touchUpInside)
        Button3.tag=3
        Button3.addTarget(self,action:#selector(buttonClicked),
                          for:.touchUpInside)
    
    }
    
    func buttonClicked(sender:UIButton)
    {
        switch sender.tag
        {
            case 1: print("1")     //when Button1 is clicked...
                break
            case 2: print("2")     //when Button2 is clicked...
                break
            case 3: print("3")     //when Button3 is clicked...
                break
            default: print("Other...")
        }
    }
    
    0 讨论(0)
提交回复
热议问题