Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply both bold and italic font to an NSAttributedString?

I'm trying to parse my own HTML string into an NSAttributedString for rendering in a UITextView.

So, for when the string appears as such:

<strong><em>This should be both bold and italic</strong></em>

I want to apply a distinct bold and italic font to the eventual NSAttributedString, so that if the user ever removes either the bold or italic font from it during editing, one of the remaining fonts will stay intact.

This is the main reason why I don't simply want to apply a single font style like bold-italic, as other SO answers have suggested.

like image 414
NYC Tech Engineer Avatar asked Sep 24 '14 17:09

NYC Tech Engineer


People also ask

How do you make text bold and italicized?

To make text bold, select and highlight the text first. Then hold down Ctrl (the control key) on the keyboard and press B on the keyboard. To make text italic, select and highlight the text first. Then hold down Ctrl (the control key) on the keyboard and then press the I on the keyboard.

How do I put fonts in italics?

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

How do you make a string bold in Swift?

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

How do you add attributed text in Swift?

Changing an Attributed String First create an NSMutableAttributedString with a new font attribute. You don't use textView. text . Then append another attributed string that doesn't have any attributes set.


1 Answers

Here is my answer after looking through different sources:

UIFontDescriptor *fontDescriptor = [UIFontDescriptor preferredFontDescriptorWithTextStyle:UIFontTextStyleBody];

UIFontDescriptor *changedFontDescriptor;      
NSDictionary *attributes;

uint32_t existingTraitsWithNewTrait = [fontDescriptor symbolicTraits] | UIFontDescriptorTraitBold | UIFontDescriptorTraitItalic;
changedFontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:existingTraitsWithNewTrait];

UIFont *updatedFont = [UIFont fontWithDescriptor:changedFontDescriptor size:0.0];

attributes = @{ NSFontAttributeName : updatedFont };

attributedString = [[NSAttributedString alloc] initWithString:yourString attributes:attributes];
like image 108
NYC Tech Engineer Avatar answered Oct 06 '22 01:10

NYC Tech Engineer