如何在Swift中使用一个IBAction用于多个按钮? [英] How to use one IBAction for multiple buttons in Swift?

查看:637
本文介绍了如何在Swift中使用一个IBAction用于多个按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个按钮,每个按钮都可以切换应用程序的语言。而不是必须为每个按钮创建多个IBAction是否有办法让它们都连接到一个IBAction并根据按下的按钮更改语言?我认为在这种情况下使用switch语句会很好,但不能确定如何设置它。

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 them all connected to one IBAction and change the language based on the button pressed? I'm thinking a switch statement would be good to use in this situation but not exactly sure how to set it up.

推荐答案

在Interface Builder中,选择Attributes Inspector并为每个按钮设置一个唯一编号的Tag,然后您可以执行以下操作:

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
    }
}

将动作连接到多个按钮:在Interface Builder中,右键单击视图层次结构中的ViewController,然后单击鼠标左键以将操作连接拖动到每个按钮。

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.

这篇关于如何在Swift中使用一个IBAction用于多个按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆