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 NSRange
s 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
.