Given a string, The * quick * brown * fox * jumps * over * the * lazy * dog, I'm applying font modifiers as follows in order to style all occurrences of asterisk differently than the rest of the text.
func customDesc(_ text: String) -> NSMutableAttributedString {
let asteriskTextRange = (text as NSString).range(of: "*")
let attributedString = NSMutableAttributedString(string: text, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15, weight: .semibold)])
attributedString.setAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20, weight: .heavy)], range: asteriskTextRange)
return attributedString
}
It seems range(of:) will only pick the first occurrence so how do update all occurrences and display the resultant text in a Text view? I could not find any initialisers that accept NSMutableAttributedString. Any help is appreciated.
Texts take the SwiftAttributedStrings instead of theNSAttributedStrings from Objective-C. You can convert toAttributedStringsimply by using one of its initialisers.However, I would suggest that
customDescreturn aAttributedStringdirectly, as it is more Swifty. You can useranges(of:)to find all the ranges of a particular substring.