设置“AppleLanguages”不会更改应用程序语言

时间:2015-06-10 07:10:18

标签: ios swift ios8

我正在尝试实现可以​​更改应用语言的功能 我试着像这样设置:

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("de", forKey: "AppleLanguages")

应用程序重启后语言仍然是“系统默认” 现在我通过设置Scheme > Application Language > language来测试不同的语言 但是,用户是否可以单击按钮并在重新启动后查看选择的语言?

还有什么方法可以避免在重启时更改语言?

7 个答案:

答案 0 :(得分:10)

您必须使用数组设置AppleLanguages键,而不是字符串:

UserDefaults.standard.set(["de"], forKey: "AppleLanguages")

答案 1 :(得分:6)

是的,您可以立即更改应用语言,

var language = "de"
let path = NSBundle.mainBundle().pathForResource(language, ofType: "lproj")
let bundle = NSBundle(path: path!)
let string = bundle?.localizedStringForKey("key", value: nil, table: nil)

将您的NSUserDefaults值用于语言。

答案 2 :(得分:5)

以下是在swift -

中启动前更改语言的方法

假设我想强制Hebrew本地化:

1。创建自己的Main.swift类

import Foundation
import UIKit

// Your initialization code here
let langCultureCode: String = "he_IL"
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject([langCultureCode], forKey: "AppleLanguages")
defaults.synchronize()

UIApplicationMain(Process.argc, Process.unsafeArgv, nil, NSStringFromClass(AppDelegate))

2。删除您的AppDelegate.swift“主要”责任

//@UIApplicationMain <-- COMMENT THIS OUT
class AppDelegate: UIResponder, UIApplicationDelegate 

这将使您的应用程序强制进入区域设置而无需任何启动

答案 3 :(得分:1)

如果用于测试目的,只需更改模拟器设置应用程序中的语言 如果你想在你的应用程序中创建一种语言选择器,它很漂亮painful而且我认为你不应该这样。
您的应用程序从设备读取语言和区域设置,并相应地更改UI。
覆盖此行为非常困难,您将无法完成语言的完整更改,例如,如果您尝试在应用程序中显示地图并且设备语言是西班牙语,但应用语言是英语,您将看到用西班牙语写的地图指示 Here一个可以提供帮助的项目。

答案 4 :(得分:0)

您可以在AppDelegate.swift中尝试下面,虽然更改不会立即出现,但在您杀死并重新启动应用程序之后。 -

NSUserDefaults.standardUserDefaults().removeObjectForKey("AppleLanguages")
NSUserDefaults.standardUserDefaults().setObject(["de"], forKey: "AppleLanguages"   
NSUserDefaults.standardUserDefaults().synchronize()

答案 5 :(得分:0)

@royherma的答案中提到的main.swift文件的更新的Swift语法。这样可以避免在覆盖UserDefaults设置后必须重新启动应用程序:

import Foundation
import UIKit

// Your initialization code here
let langCultureCode: String = "LANGUAGE_CODE"

UserDefaults.standard.set([langCultureCode], forKey: "AppleLanguages")
UserDefaults.standard.synchronize()

UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(AppDelegate.self))

@UIApplicationMain文件中的AppDelegate.swift配对在一起。

答案 6 :(得分:0)

此解决方案对我有用:
1.创建Bundle的扩展



    import Foundation

    class L012Localizer: NSObject {
        class func DoTheSwizzling() {
            MethodSwizzleGivenClassName(cls: Bundle.self, originalSelector: #selector(Bundle.localizedString(forKey:value:table:)), overrideSelector:
                #selector(Bundle.specialLocalizedString(key:value:table:)))
        }
    }

    extension Bundle {
        @objc func specialLocalizedString(key: String, value: String?, table tableName: String?) -> String {
            let currentLanguage = Utils.currentLanguage().rawValue
            var bundle = Bundle();
            if currentLanguage != "" , let _path = Bundle.main.path(forResource: currentLanguage, ofType: "lproj") {
                bundle = Bundle(path: _path)!
            } else {
                let _path = Bundle.main.path(forResource: "Base", ofType: "lproj")!
                bundle = Bundle(path: _path)!
            }
            return (bundle.specialLocalizedString(key: key, value: value, table: tableName))
        }
    }

    func MethodSwizzleGivenClassName(cls: AnyClass, originalSelector: Selector, overrideSelector: Selector){

        let origMethod: Method = class_getInstanceMethod(cls, originalSelector)!;
        let overrideMethod: Method = class_getInstanceMethod(cls, overrideSelector)!;
        if (class_addMethod(cls, originalSelector, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) {
            class_replaceMethod(cls, overrideSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
        } else {
            method_exchangeImplementations(origMethod, overrideMethod);
        }
    }


2.在 AppDelegate 中调用 DoTheSwizzling




     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            L012Localizer.DoTheSwizzling()
            return true
        }


3.创建语言实用程序



    class Utils: NSObject {
        class func setLanguage(_ lang: LanguageType) {
            UserDefaults.standard.set([lang.rawValue], forKey: "AppleLanguages")
        }

        class func currentLanguage() -> LanguageType {
            if let langs = UserDefaults.standard.object(forKey: "AppleLanguages") as? [String], let currentLang = langs.first {
                return LanguageType(rawValue: currentLang) ?? .english
            }

            return .english
        }
    }


4.创建语言类型



    enum LanguageType: String {
        case english = "en"
        case korea = "ko"
        case vietnamese = "vi-VN"

        func toString() -> String {
            switch self {
            case .korea:
                return "Korea".localized
            case .vietnamese:
                return "Vietnamese".localized
            default:
                return "English".localized
            }
        }
    }


5.请记住,您必须在方案中将应用程序语言配置为 SystemLanguage
enter image description here
6.然后,每当您需要对应用程序进行本地化时,只需要调用即可。 Utils.setLanguage({LanguageType})