代码之家  ›  专栏  ›  技术社区  ›  J. Doe

NSLocalizedString中参数的不同字体

  •  1
  • J. Doe  · 技术社区  · 6 年前

    NSMutableAttributedString . 但是,我不确定如何设置以下案例的格式:

    String(format: NSLocalizedString("%@ has replied in '%@'", comment: ""), username, conversationTitle)
    

    我想给用户名和对话标题一个单独的字体。我想用一种不那么麻烦的方式来做这件事。我的意思是:

    • username 稍后,在字符串中使用子字符串。当 conversationTitle 是一样的 用户名 ,或 会话标题 用户名 等等等等。。
    • 我不想构建字符串,如下所示: https://stackoverflow.com/a/37992022/7715250 NSLocalizedString's

    Making text bold using attributed string in swift , Are there approaches for using attributed strings in combination with localization? 其他的大部分是字符串文本,没有 NSLocalizedString NSLocalizedString 使用参数。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Larme    6 年前

    首先,您的.string中应该有一个更通用、更可读的键,例如:

    "_REPLIED_IN_" = "%@ has replied in %@";
    

    不要像您在示例中所做的那样混淆键和值。 此外,稍后更容易看到代码中是否存在未本地化的硬编码字符串。

    现在,有一个问题,因为在英语中,它可能是按顺序排列的,但在其他语言中不一定。

    因此:

    "_REPLIED_IN_" = "%1$@ has replied in %$2@";
    

    现在,我将使用粗体示例,因为它更简单,但您可以使用一些自定义标记来告诉您它需要粗体,如HTML、MarkDown等。

    "_REPLIED_IN_" = "<b>%1$@</b> has replied in <b>%$2@</b>";
    

    您需要将其解析为 NSAttributedString :

    let translation = String(format: NSLocalizedString(format: "_REPLIED_IN_", comment: nil), userName, conversationTitle)
    let attributedText = NSAttributedString.someMethodThatParseYourTags(translation)