ios - 无需重启应用程序即可快速切换应用程序语言

标签 ios swift localization

我希望我的应用程序语言在单击按钮时发生变化..

我的代码是:

@IBAction func convertlang(_ sender: Any) {
   if L102Language.currentAppleLanguage() == "en" {
        L102Language.setAppleLAnguageTo(lang: "ar")
        UIView.appearance().semanticContentAttribute = .forceRightToLeft
    } else {
        L102Language.setAppleLAnguageTo(lang: "en")
        UIView.appearance().semanticContentAttribute = .forceLeftToRight
    }
}

let APPLE_LANGUAGE_KEY = "AppleLanguages"
class L102Language {
    class func currentAppleLanguage() -> String{
         let userdef = UserDefaults.standard
         let langArray = userdef.object(forKey: APPLE_LANGUAGE_KEY) as! NSArray
         let current = langArray.firstObject as! String
    return current
}

class func setAppleLAnguageTo(lang: String) {
    let userdef = UserDefaults.standard
    userdef.set([lang,currentAppleLanguage()], forKey: APPLE_LANGUAGE_KEY)
    userdef.synchronize()
}}

这很好用,当我点击按钮时转换语言..

问题是我需要重新启动应用程序才能看到语言更改..

我搜索过这个,但其中大部分是针对 objective-c 的,并尝试了一些针对 swift 但没有用..

如何做到这一点?

最佳答案

您无法通过正常的按钮单击在运行时更改语言。如果您真的需要它,则需要改用自定义本地化系统。

为了在运行时更改应用程序语言,我通过创建两个不同的 Storyboard手动完成了此操作。我在 NSUserDefaults 中保存了语言首选项,但没有使用键 AppleLanguages,然后调用 AppDelegate 的 didFinishLaunchingWithOptions 方法来选择 Storyboard。

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainEnglish" bundle:nil];
UINavigationController *navigationcontroller=[[UINavigationController alloc]init];
RegistorViewController *registor=[storyboard instantiateViewControllerWithIdentifier:@"Registor"];
[self.window setRootViewController:navigationcontroller];
[self.window makeKeyAndVisible];
[navigationvontroller pushViewController:registor animated:NO];

虽然这不是苹果希望开发人员在运行时做的事情。

Someone even asked an Apple engineer这是回应:

In general, you should not change the iOS system language (via use of the AppleLanguages pref key) from within your application. This goes against the basic iOS user model for switching languages in the Settings app, and also uses a preference key that is not documented, meaning that at some point in the future, the key name could change, which would break your application.

If you want to switch languages in your application, you can do so via manually loading resource files in your bundle. You can use NSBundle:pathForResource:ofType:inDirectory:forLocalization: for this purpose, but keep in mind that your application would be responsible for all loading of localized data.

关于ios - 无需重启应用程序即可快速切换应用程序语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49773929/

相关文章:

java - 如何根据设置本地化程序文本?

ios - Apple B2B 应用程序如何使用兑换码通过 VPP 分发

ios - swift:如何请求 HealtKit 许可?

ios - 使用批处理在 Firestore 内增加值 - "Ambiguous use of ' 增量'"

ios - 从服务器加载图像到标签栏项目

ios - 如何保持本地化 Storyboard 或 XIB 同步?

iphone - 如何以编程方式绘制 eclipse 刻线以用作普通 tableview 中的分隔符

ios - 设置内容插入后,iOS7 上的 UIWebView 中的部分黑色背景

android - 从 Firebase 向 Android 和 iOS 发送推送通知

wpf - 如何为 WPFLocalizationExtension 本地化 Xaml 文件中的字符串