ios - 如何在 Swift 中以编程方式从字符串文件中获取本地化语言?
问题描述
如何使用 Xcode 12 在 Swift 中以编程方式获取所有检查的本地化语言?
我想将这些语言放在一个可以显示为选择器视图的数组中,以便用户可以无缝更改语言,而无需更改其设备的语言。我想避免硬编码。
解决方案
这可能会奏效:
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
,但你明白了......
推荐阅读
- ios - 在 iOS 的 MapKit 中显示一张特定的国家地图
- typescript - 即使之前有检查,VSCode TypeScript Map get 仍然被认为是未定义的
- java - 用于执行 Java 控制台应用程序的 Bash 脚本
- excel - 比较单元格中逗号分隔的字母数字字符
- java - 我的 spring-boot 程序在属性中没有 JavaBuilder
- android - 突然在下载 maven-metadata.xml Android Studio 时构建卡住了
- python - Swagger UI 将身份验证令牌传递给 API 调用
- sorting - 所以我需要在pascal中对字母结构数据进行排序,我即兴创作了一种排序方法,但是有一个错误idk如何修复
- json - Angular environment.ts 问题 JSON。但是 environment.prod.ts
- authentication - 如何在未经授权的 api 请求后自动重定向登录(例如,令牌过期时)?- Nuxt 认证模块