所以我的字符串有一个扩展名。我在项目中使用简体中文和繁体中文。我试图手动切换字符串的语言,但是

Bundle(path: URL(fileURLWithPath: bundlePath ?? "").deletingLastPathComponent().absoluteString)


总是返回nil。我在Xcode项目中有本地化的字符串。有人可以帮忙吗?

 extension String {
    var localized: String {

        //zh-Hans.lproj
        let lang = UserDefaults.standard.string(forKey: "i18n_language")
        let bundlePath: String? = Bundle.main.path(forResource: "Localizable", ofType: "strings", inDirectory: nil, forLocalization: "zh-Hans")
        print("bundlePath = \(String(describing: bundlePath!))")
        // here i get path as bundlePath = /var/containers/Bundle/Application/C3xx3D-BxxC-4Dx3-xx8D-156xxxxxxx3D/xxxx.app/zh-Hans.lproj/Localizable.strings
        let langBundle = Bundle(path: URL(fileURLWithPath: bundlePath ?? "").deletingLastPathComponent().absoluteString)
        print("langBundle = \(langBundle)") // getting nil

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

最佳答案

您得到零是因为没有将bundlePath转换为URL。

在这一行:

let langBundle = Bundle(path: URL(fileURLWithPath: bundlePath ?? "").deletingLastPathComponent().absoluteString)


像这样尝试:

let langBundle = Bundle(path: URL(fileURLWithPath: "file://\(bundlePath)" ?? "").deletingLastPathComponent().absoluteString)


但是,为什么要将字符串转换为URL然后又转换为string?您可以直接这样做:

let bundlePath: String? = Bundle.main.path(forResource: "Localizable", ofType: "strings", inDirectory: nil, forLocalization: "zh-Hans")
print("bundlePath = \(String(describing: bundlePath!))")
// here i get path as bundlePath = /var/containers/Bundle/Application/C3xx3D-BxxC-4Dx3-xx8D-156xxxxxxx3D/xxxx.app/zh-Hans.lproj/Localizable.strings

if let bundlePathString = bundlePath{
   let langBundle = Bundle.init(path: bundlePathString)
    print("langBundle = \(String(describing: langBundle))")
}

关于ios - 为什么我的语言包路径在iOS Swift中返回nil?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48740993/

10-13 01:40