首页 > 解决方案 > 如何在 Swift 中以编程方式从字符串文件中获取本地化语言?

问题描述

如何使用 Xcode 12 在 Swift 中以编程方式获取所有检查的本地化语言?

我想将这些语言放在一个可以显示为选择器视图的数组中,以便用户可以无缝更改语言,而无需更改其设备的语言。我想避免硬编码。

我的 .strings 文件中 Xcode 中的本地化复选框的屏幕截图

标签: iosswiftxcodelocalization

解决方案


这可能会奏效:

func localizations() -> [String] {
    guard let contentsURLs = try? FileManager.default.contentsOfDirectory(at: Bundle.main.bundleURL, includingPropertiesForKeys: nil) else { return [] }
    let identifiers = contentsURLs.compactMap { anURL -> String? in
        guard anURL.pathExtension == "lproj" else { return nil }
        return anURL.deletingPathExtension().lastPathComponent
    }

    let humanReadableNames = identifiers.compactMap { anIdentifier in
        return Locale.current.localizedString(forIdentifier: anIdentifier)?.localizedCapitalized
    }

    return humanReadableNames
}

我什至将它们转换为人类可读的语言名称,而不是使用例如“中文(简体)”的“zh-Hans”。当然,如果你自己处理你的语言环境,你可能想使用不同的Locale.current,但你明白了......


推荐阅读