问题描述
我有多个按钮,每个按钮都可以切换应用程序的语言.不必为每个按钮创建多个 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!