如何在 Swift 中为多个按钮使用一个 IBAction?

How to use one IBAction for multiple buttons in Swift?(如何在 Swift 中为多个按钮使用一个 IBAction?)
本文介绍了如何在 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)