How to use one IBAction for multiple buttons in Swift?

后端 未结 3 1259
日久生厌
日久生厌 2020-12-29 11:39

I have multiple buttons each one with the ability to switch the language of the app. Instead of having to create multiple IBActions for each button is there a way to have t

3条回答
  •  有刺的猬
    2020-12-29 11:47

    Do not set tag if you have reference to the button.

    You can just compare the reference instead of tags. This way, you won't introduce a new bug, because unlike a tag that you type yourself, reference is created by compiler automatically.

    @IBOutlet weak var firstButton: UIButton!
    @IBOutlet weak var secondButton: UIButton!
    @IBOutlet weak var thirdButton: UIButton!
    
    @IBAction changeLanguage(sender: UIButton) {
        if sender == firstButton {
    
        } else if sender == secondButton {
    
        } else if sender == thirdButton {
    
        }
    }
    

提交回复
热议问题