iOS - 在 Localizable.strings 中用粗体字符串强调

iro*_*oei 5 localization nsattributedstring localizable.strings ios swift

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

"Pending network connection" = "<b>Pending</b> network connection";
Run Code Online (Sandbox Code Playgroud)

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

 "camSave" = "To complete onboarding:\n1. Tap Save and disconnect to disconnect from the camera.\n2. Connect to the internet.\n3. Log in to Cloud.";
Run Code Online (Sandbox Code Playgroud)

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

Rat*_*ker 5

您可以像下面这样实现:

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

所以在你的情况下,文件Localizable.string将如下所示

"%@ network connection" = "%@ network connection";
"Pending" = "Pending";
Run Code Online (Sandbox Code Playgroud)

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

let complete = String(format: NSLocalizedString("%@ network connection", ""), NSLocalizedString("Pending", ""))
Run Code Online (Sandbox Code Playgroud)

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

let range = complete.range(of: NSLocalizedString("Pending", ""))
Run Code Online (Sandbox Code Playgroud)

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


Mat*_*lak 3

实际上,您可以将 HTML 标签与NSAttributedString. 这是我用的:

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)
}
Run Code Online (Sandbox Code Playgroud)

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