Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply bold and italics to an NSMutableAttributedString range?

Tags:

People also ask

How do I make text bold in string Swift?

let label = UILabel() label. attributedText = NSMutableAttributedString() . bold("Address: ") .

How do you italicize text in Swift?

To access the SwiftKey Note formatting bar, simply swipe left on the prediction bar to reveal the formatting bar. You can access options for bold, italics, and other formatting by pressing these buttons.

How do you make text font italic?

To make your selected text italic or start writing text in italic, press the Ctrl + I keys on your keyboard.


I've been trying to apply combinations of NSFontAttributes to NSMutableAttributedString's lately and I simply can't find a thorough explanation on how to do it without removing other attributes.

I've searched a bunch, and found this question pertaining to how to do it with HTML, and then this question about how to find where text has been bolded or italicized, but nothing on how to actually do it.

Currently, I try to format stings as follows:

Italics: [mutableAttributedString addAttribute: NSFontAttributeName value:[fontAttributes valueForKey:CXItalicsFontAttributeName] range:r];

Bold: [mutableAttributedString addAttribute:NSFontAttributeName value:[fontAttributes valueForKey:CXBoldFontAttributeName] range:r];

Where the constants CXItalicsFontAttributeName and CXBoldAttributeName extract the following two values from a dictionary respectfully:

UIFont *italicsFont = [UIFont fontWithName:@"Avenir-BookOblique" size:14.0f]; UIFont *boldFont = [UIFont fontWithName:@"Avenir-Heavy" size:14.0f]; 

I know this mustn't be the right way to go about formatting, as the NSAttributedString standard attributes don't include a ItalicsFontAttribute or BoldFontAttribute, but I can't find the properly way to do this. Can anyone assist me?