NSAttributedString and emojis: issue with positions and lengths

前端 未结 1 1038
情书的邮戳
情书的邮戳 2021-01-31 10:54

I\'m coloring some parts of a text coming from an API (think \"@mention\" as on Twitter) using NSAttributedString.

The API gives me the text and an array of entities rep

相关标签:
1条回答
  • 2021-01-31 11:54

    A Swift String provides different "views" on its contents. A good overview is given in "Strings in Swift 2" in the Swift Blog:

    • characters is a collection of Character values, or extended grapheme clusters.
    • unicodeScalars is a collection of Unicode scalar values.
    • utf8 is a collection of UTF–8 code units.
    • utf16 is a collection of UTF–16 code units.

    As it turned out in the discussion, pos and len from your API are indices into the Unicode scalars view.

    On the other hand, the addAttribute() method of NSMutableAttributedString takes an NSRange, i.e. the range corresponding to indices of the UTF-16 code points in an NSString.

    String provides methods to "translate" between indices of the different views (compare NSRange to Range<String.Index>):

    let text = "@ericd Some text.                                                                     
    0 讨论(0)
提交回复
热议问题