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

标签 ios swift xcode-ui-testing

我如何从主 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 目标的一部分即可访问该包。

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

关于ios - 从主包中获取本地化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41700302/

相关文章:

iphone - 如何在泄漏的“扩展详细信息”面板中显示详细信息?

swift - 在 Swift 中将 deleteRealmIfMigrationNeeded 与 Realm 一起使用时崩溃

swift - ?= 运算符在 Swift 中有什么作用?

Swift:从命令行运行时, Assets 对 UI 测试不可见

ios - iOS 12 中已启用分段控件的 Xcode UI 测试测试失败

javascript - 我如何在网站上使用 http url fallback 制作跨浏览器 native 应用程序 url?

ios - 如何在框架内加载 `.xib`/`.nib` 文件?

ios - 如何在 UITests 中选择 UITableView 的一部分?

ios - 切换保存用户首选项

ios - Swift - 标签角在tableviewcell中有不同的半径