从主bundle获取本地化字符串

时间:2017-01-17 14:57:21

标签: 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 ...

任何提示?

1 个答案:

答案 0 :(得分:6)

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

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而不是UITest bundle的捆绑

相关问题