ios - SWIFT 中类似于 UIColor.systemgray 的任何标准字符串

标签 ios swift string

在Android中,我们可以访问一些平台提供的标准字符串资源,例如cancel , OK , delete等等。这很方便,因为我不必存储那些简单文本的所有翻译。

我知道 Swift 提供了类似于 UIColor 的东西,例如UIColor.systemgray。

我的问题是:有没有类似的东西,但对于 String .谢谢!

最佳答案

从技术上讲,您可以从 Apple 自己的框架加载本地化字符串。例如,从 UIKit 加载,你会使用

let bundle = Bundle(for: UIView.self)
let string = bundle.localizedString(forKey: "Cancel", value: nil, table: nil)

如果当前语言环境是德语,则为 "Abbrechen" .

这种方法的缺点是您只能在运行时知道框架中是否存在特定字符串。

我能想到的最佳解决方法是定义您自己使用的 key ,并通过单元测试不断验证它们。

例如,您可以将所有系统字符串键收集在一个大小写可迭代的枚举中
public enum SystemStringKey: String, CaseIterable {
    case cancel = "Cancel"
    ...
}

并使用它们通过 String 上的扩展名加载系统字符串
public extension String {
    static var systemStringBundle: Bundle {
        return Bundle(for: UIView.self)
    }

    static func systemString(for key: SystemStringKey) -> String {
        return systemStringBundle.localizedString(forKey: key.rawValue, value: nil, table: nil)
    }
}

然后,您可以在代码中使用系统字符串,如常量
label.text = .systemString(for: .cancel)

要验证它们的持续存在,您可以使用这样的单元测试
class SystemStringKeyTests: XCTestCase {

    func testAllKeysExist() throws {
        let path = try XCTUnwrap(String.systemStringBundle.path(forResource: "Localizable", ofType: "strings"))
        let dict = try XCTUnwrap(NSDictionary(contentsOfFile: path))
        for key in SystemStringKey.allCases {
            XCTAssertNotNil(dict[key.rawValue])
        }
    }

}

这不是 100% 防弹的,因为 Apple 在 iOS 更新中删除了一个字符串,然后任何依赖该字符串的已发布应用程序都会显示未翻译的英文字符串,直到您自己发布更新。

更新:我拼凑了一个 Swift 包,以便方便地探索和访问系统包中的可用字符串。不过有一些警告。见 https://nosuchdomain.mooo.com/git/doc/swift-systemstrings了解更多信息。

关于ios - SWIFT 中类似于 UIColor.systemgray 的任何标准字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61339440/

相关文章:

c - 将字符串从 Swift 传递到 C 回 Swift

swift - 在 iOS 8 中动态更改 ScrollViews subview

java - 在 Java 中完美散列三个字母的小写字符串的最佳方法?

android - 在 iOS 的 ReactJS 中显示十进制键盘

ios - 按年、月、日排序时出现问题

ios - Realm 模型中的递归关系

iOS 阻止默认图像对焦

ios - NSLayoutConstraints 可以用十进制常量渲染吗?

c# - 格式化以下字符串的 Java 等价物是什么?

c# - 如何将字符串解析为 BigInteger?