Get button pressed id on Swift via sender

后端 未结 15 1121
广开言路
广开言路 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: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
        }
    }
    

提交回复
热议问题