【问题标题】:How to find all available Strings-Tables in iOS project?如何在 iOS 项目中找到所有可用的字符串表?
【发布时间】:2021-05-27 09:20:12
【问题描述】:

是否可以找到 iOS 项目中可用的所有本地化表格?


背景:

在一个基于 Swift 的 iOS 项目中,我使用了多个本地化的 .strings 文件。例如一个文件包含不同项目中使用的通用字符串,一个文件项目特定字符串等。

使用自定义本地化方法可以正常工作,该方法检查是否在文件/表 A 中找到给定字符串,如果未找到翻译,则继续在文件/表 B 中搜索:

func localizedString(forKey key: String) -> String {
    // Search in project specific, default file Localizable.strings
    var result = Bundle.main.localizedString(forKey: key, value: nil, table: nil)

    // If now translation was found, continue search in shared file "Common.strings"
    if result == key {
        result = Bundle.main.localizedString(forKey: key, value: nil, table: "Common")
    }

    if result == key {
        result = Bundle.main.localizedString(forKey: key, value: nil, table: "OtherFile")
    }

    ...

    return result
}

是否可以将此扩展为更通用的解决方案,我不必手动指定文件/表,而是自动完成?这将允许在具有不同字符串文件的不同项目中使用相同的代码。

// PSEUDOCODE    
func localizedString(forKey key: String) -> String {
    for tableName in Bundle.main.allLocalizdationTables {   // DOES NOT EXIST...
        var result = Bundle.main.localizedString(forKey: key, value: nil, table: tableName)

        if result != key {
            return result 
        }
    }

    return key
}

所以:有没有可能

【问题讨论】:

  • Bundle.main.urls(forResourcesWithExtension: "strings", subdirectory: nil) 可能会有所帮助。获取所有 URL,然后提取文件名...
  • 谢谢@Larme 我不知道.strings 文件实际上包含在编译的Bundle 中,但确实如此。如果您想将此添加为答案,我可以接受。

标签: swift localization nsbundle nslocalizedstring


【解决方案1】:

这应该可以解决问题:

func localizedString(forKey key: String) -> String {
    guard let filesURL = Bundle.main.urls(forResourcesWithExtension: "strings", subdirectory: nil) else { return key }
    let tablesName = filesURL.map { $0.deletingPathExtension().lastPathComponent }
    for aTableName in tablesName {
        var result = Bundle.main.localizedString(forKey: key, value: nil, table: aTableName)
        if result != key {
            return result
        }
    }
    return key
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多