How to use one IBAction for multiple buttons in Swift?

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

    In Interface Builder, select the Attributes Inspector and set the Tag for each button with a unique number, then you can do something like this:

    @IBAction changeLanguage(sender: AnyObject) {
        guard let button = sender as? UIButton else {
            return
        }
    
        switch button.tag {
        case 1:
            // Change to English
        case 2:
            // Change to Spanish
        case 3:
            // Change to French, etc
        default:
            print("Unknown language")
            return
        }
    }
    

    To connect the action to multiple buttons: in Interface Builder, right-click ViewController in the view hierarchy, then left-click to drag the action connection to each button.

提交回复
热议问题