从主包中获取本地化字符串

Get localized strings from main bundle

我如何从主 Bundle 进入 UITest 目标本地化?

func localizedText(_ key: String) -> String {
    return Bundle.main.localizedString(forKey: key, value: nil, table: nil)
}

我尝试访问 Bundle.main 但没有本地化字符串。而且我似乎无法导入应用程序的主要目标来执行 Bundle(for: ClassName.self).localized...

有什么提示吗?

要在 UITest 中使用本地化字符串,您必须做两件事:

1) 将您的 Localizable.strings 文件添加到您的 UITest 目标

2) 通过 UITest 包访问字符串:

func localizedText(_ key: String) -> String {
    let uiTestBundle = Bundle(for: AClassFromYourUITests.self)
    return NSLocalizedString(key, bundle: uiTestBundle, comment: "")
}

只需确保您使用作为 UITest 目标一部分的 class 来访问包。

在 运行 UITests 时使用 Bundle.main 不起作用,因为它为您提供了 UITest Runner App 的捆绑包而不是 UITest 捆绑包