ios – 强制本地化内部框架,如UIKit,无需重启App

前端之家收集整理的这篇文章主要介绍了ios – 强制本地化内部框架,如UIKit,无需重启App前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我必须在应用程序中添加一个切换语言的选项.
我只是坚持本地化内部framworks.任何人都可以帮助我从应用程序本身的内部框架本地化,如UIKit等,而无需重新启动.我的代码工作正常,但对于内部框架的情况需要重新启动.只是内部框架没有得到本地化.

我目前的代码是:

创建一个名为BundleExtension.swift文件,并将以下代码添加到其中 –

var bundleKey: UInt8 = 0

class AnyLanguageBundle: Bundle {

override func localizedString(forKey key: String,value: String?,table tableName: String?) -> String {

    guard let path = objc_getAssociatedObject(self,&bundleKey) as? String,let bundle = Bundle(path: path) else {

            return super.localizedString(forKey: key,value: value,table: tableName)
    }

    return bundle.localizedString(forKey: key,table: tableName)
  }
}

extension Bundle {

class func setLanguage(_ language: String) {

    defer {

        object_setClass(Bundle.main,AnyLanguageBundle.self)
    }

    objc_setAssociatedObject(Bundle.main,&bundleKey,Bundle.main.path(forResource: language,ofType: "lproj"),.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  }
}

现在,无论何时需要更改语言,都可以调用方法

func languageButtonAction() {
    // This is done so that network calls now have the Accept-Language as "hi" (Using Alamofire) Check if you can remove these
    UserDefaults.standard.set(["hi"],forKey: "AppleLanguages")
    UserDefaults.standard.synchronize()

    // Update the language by swaping bundle
    Bundle.setLanguage("hi")

    // Done to reintantiate the storyboards instantly
    let storyboard = UIStoryboard.init(name: "Main",bundle: nil)
    UIApplication.shared.keyWindow?.rootViewController = storyboard.instantiateInitialViewController()
}

解决方法

查看此演示,它将适合您.

Link

猜你在找的iOS相关文章