Get button pressed id on Swift via sender

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

提交回复
热议问题