【问题标题】:iOS - Emphasise with bold strings in Localizable.stringsiOS - 在 Localizable.strings 中用粗体字强调
【发布时间】:2021-08-06 04:11:05
【问题描述】:

有没有办法像这样在 Localizable 文件中加粗一些单词?

"Pending network connection" = "<b>Pending</b> network connection";

我有这个字符串,我只想强调某些单词:

 "camSave" = "To complete onboarding:\n1. Tap Save and disconnect to disconnect from the camera.\n2. Connect to the internet.\n3. Log in to Cloud.";

顺便说一句,我想在警报中使用它

【问题讨论】:

    标签: ios swift localization nsattributedstring localizable.strings


    【解决方案1】:

    您实际上可以使用带有NSAttributedString 的HTML 标记。这是我用的:

    static func convertFromHTMLString(_ input: String?) -> NSAttributedString? {
        guard let input = input else { return nil }
    
        guard let data = input.data(using: String.Encoding.unicode, allowLossyConversion: true) else { return nil  }
        return try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil)
    }
    

    所以我使用 UTF8 格式将输入字符串转换为原始数据。然后我使用属性字符串的构造函数和使用适当标志NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html的数据。

    【讨论】:

    • 你如何使用它?我想在 ui alert title 中实现它
    • @ironRoei 我认为本机警报视图不支持这一点。您必须创建一个自定义警报视图来执行此操作。之后,我假设您将在其中使用标签作为标题,因此 label.attributedText = convertFromHTMLString(myLocalizedString).
    【解决方案2】:

    您可以通过以下方式实现:

    1. 将字符串分解为模板和参数格式。
    2. 提供个性化的本地化服务。
    3. 从模板和参数组成完整的字符串。
    4. 在完整字符串中查找参数并使用NSAttributedString 应用格式。

    因此,在您的情况下,Localizable.string 文件将如下所示

    "%@ network connection" = "%@ network connection";
    "Pending" = "Pending";
    

    现在形成完整的本地化字符串

    let complete = String(format: NSLocalizedString("%@ network connection", ""), NSLocalizedString("Pending", ""))
    

    然后在完整字符串中找到参数化字符串的Range

    let range = complete.range(of: NSLocalizedString("Pending", ""))
    

    现在通过形成NSAttributedString 来应用您需要在此范围内应用的任何属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      相关资源
      最近更新 更多