I have a string let’s say " my name is %@ and i study in class %@" now I want to bold the placeholder text which i will be inserting , so that the result will look something like this:" My name is Harsh and i study in class 10" and i will display it on a label
I have already tried using NSAttributedString but since the string will be localised i am not able to use the range parameter of attributed string to make it bold.
3
Answers
I can offer a naive solution using
NSRegularExpression
without any complex / scary regex. I am sure there are more optimal solutions than this.The steps are quite close to what meaning matters has posted above
locations array
NSMutableAttributedString
from the updated localized stringNSMutableAttributedString
defined by thelocations array
Here is the code I used with some comments to explain:
The end result:
Bold part of localised string Parameterised string bold Swift NSAttributedString iOS
This should be flexible enough to work with any number of placeholders that are present in strings and you do not need to keep track of different placeholders.
for more references, use this
There are different ways to do so, but in my opinion, one of the easiest way would be to use tags:
Use tags around the placeholders (and other parts if needed):
Tags can be HTML, Markdown, BBCode, or any custom you’d like, then, replace the placeholder values:
Now, depending on how you want to do it, or which tag you used, you can use the init of
NSAttributedString
from HTML, Markdown, etc, or simply usingNSAttributedString(string: localized)
, look yourself for the tags and apply the render effect needed.Here’s a little example:
Output: