Get button pressed id on Swift via sender

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

    Use the outlets instead, tags clutter the code and make the readability way worse. Think about the poor developer that reads the code next and sees if sender.tag = 381 { // do some magic }, it just won't make any sense.

    My example:

    class PhoneNumberCell: UITableViewCell {
      @IBOutlet weak var callButton: UIButton!
      @IBOutlet weak var messageButton: UIButton!
    
      @IBAction func didSelectAction(_ sender: UIButton) {
        if sender == callButton {
          debugPrint("Call person")
        } else if sender == messageButton {
          debugPrint("Message person")
        }
      }
    
      [...]
    }
    

    You could also do this in a nice switch as well, which would make it even better.

    Tested on Swift 5.1

提交回复
热议问题