How to use one IBAction for multiple buttons in Swift?

后端 未结 3 1289
日久生厌
日久生厌 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 12:01

    Yes, a switch statement is the way to go here. For a UIButton, you link it to a selector that is called when the user interacts with the button, generally the TouchUpInside event. The addTarget method, and valid selector signatures (apple.com) Of these, you want to use a method in the format @IBAction func doSomething(sender: UIButton) or @IBAction func doSomething(sender: UIButton, forEvent event: UIEvent), so that a reference to the button that triggered the event is passed to the selector.

    In your ViewController code, you'll have references to your UIButtons (possibly in a storyboard, or created manually.) Let's say you have

    @IBOutlet weak var frenchButton: UIButton!
    @IBOutlet weak var spanishButton: UIButton!
    @IBOutlet weak var englishButton: UIButton!
    

    You would connect all of them to the same method, and branch the logic based on which one was the sender. e.g.:

    @IBAction func changeLanguage(sender: UIButton) {
        switch sender {
        case frenchButton:
            // Change Language to French
            print ("C'est si bon")
        case spanishButton:
            // or Spanish
            print ("Muy Bueno")
        case englishButton:
            // or English
            print ("It's pretty cool")
        default:
            break
    
        }
    
    }
    

    Note: Case statements in Swift must be exhaustive, so you have to include a default case, even though it should never be called.

提交回复
热议问题