gpt4 book ai didi

ios - 本地化 Swizzling 使用选择器更改语言 swift4

转载 作者:行者123 更新时间:2023-11-29 11:34:34 25 4
gpt4 key购买 nike

我正在尝试更改应用程序语言并使用 Swizzling 函数,但在调用 DoTheSwizzling() 时出现问题,选择器崩溃了!我认为找不到“specialLocalizedStringForKey”所以它给了我 nil,我不知道出了什么问题?

 class Languages {

class func DoTheSwizzling() {

MethodSwizzleGivenClassName(cls: Bundle.self, originalSelector: #selector(Bundle.localizedString(forKey:value:table:)), overrideSelector: Selector(("specialLocalizedStringForKey:value:table:")))
}
}

extension Bundle {
func specialLocalizedStringForKey(key: String, value: String?, table tableName: String?) -> String {
let currentLanguage = Languages.currentAppleLanguage()
var bundle = Bundle();
if 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.specialLocalizedStringForKey(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);
}
}

enter image description here

最佳答案

Localizable.strings(英文)

"Home" = "Home";

Localizable.strings(阿拉伯语)

"Home" = "Home Arabic";

EX:LanguageFile 的 NSObject 类名

 var home = "Home".localized(lang:"Your language")//en , ar

你的字符串扩展

extension String {
func localized(lang:String) ->String {
//print(lang)
let path = Bundle.main.path(forResource: lang, ofType: "lproj")
let bundle = Bundle(path: path!)

return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
}

在你的 View Controller 中

print(LanguageFile().home)

您可以根据您的应用语言获取字符串。

你可以试试这个例子 https://github.com/karthickkck315/Language

关于ios - 本地化 Swizzling 使用选择器更改语言 swift4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50520050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com