0

I am a bit confused how I can add attributed components to text when I do not know upfront where the add the keys to. I am building a chat app and I am using UITextView to display messages between users.

I want to support tagging users. So when a user mentions another user in a message, I want to make the username of the tagged person bold. The problem is that:

  • The text which users are dynamic
  • The usernames are dynamic (ofcourse)

I don't understand how I can make this work because I need to provide NSRanges to NSAttributedString. I don't know how I can find them. What I can do, which might help, is add metadata in the original String to find out where usernames are. So I can operate on this string:

Hi @%Jhon Doe%@, do you like to speak to @%The Manager%@

And this must be transformed to (just an example with bold italic traits) attributed text on UITextView:

Hi Jhon Doe, do you like to speak to The Manager

Please note that the @% prefix and suffix are just something out of my head, it can be anything.

I am wondering now how I can make this work. Using Regex to find usernames? But how will I get the NSRange from it? Find methods on String?

I am having a hard time converting a Range to NSRange. I am also confused with UTF-16 the NSRange uses. I am just using UTF-8. Since I am having so much trouble, I was wondering if there is an easy way.

I asked a similar question the other day, but that was just attributed text at the start/ending of another String: Adding attribute to markdown NSAttributedString goes out of bounds. This question is specific about attributed text somewhere, not predefined in a String.

J. Doe
  • 12,159
  • 9
  • 60
  • 114
  • I can't quite understand what does "The text which users are dynamic" mean, could you please explain and provide examples? – Vadim Belyaev May 24 '22 at 21:08
  • 1
    Since I've already answered similar question, you can use https://stackoverflow.com/questions/71525773/change-word-colour-from-sentence-with-regex/71526873#71526873 https://stackoverflow.com/questions/54124406/make-patterns-to-use-nsregularexpression/54127239#54127239 You could adapt them. The `NSRange` are inside hte `NSTextCheckResult`, and you need to iterate by "reverse" order (to avoid range issues). – Larme May 25 '22 at 06:12
  • @Larme Thanks, I think I got it working with one of the solutions you mentioned :) I upvoted it! – J. Doe May 25 '22 at 07:28
  • If you still have issue, do no hesitate to edit your question with current code (which I guess is adapted from mine), and we might help to debug ;) – Larme May 25 '22 at 07:31

0 Answers0