user4341515
user4341515

Reputation: 35

How to programmatically style text in a Text View?

When using Text View object in Xcode > storyboard, how could I style the text of a Text View object? Programmatically or otherwise?

Upvotes: 1

Views: 376

Answers (1)

GlennRay
GlennRay

Reputation: 979

Yes, NSAttributedString is one answer, as is an NSMutableAttributedString.

After creating the string (here called aboutTextBody), you a) create styles as NSDictionary objects, b) find the range in your text string to which you want to apply that style, and c) set the attributes of the string for that range and style.

Sample code for a) is:

NSDictionary *NWStyle = [[NSDictionary alloc] init];
NWStyle = @{NSFontAttributeName:[UIFont fontWithName:@"Noteworthy-Bold" size:18.0]};

Sample code for b) and c) for the entire string is:

[aboutTextBody setAttributes:NWStyle range:NSMakeRange(0, aboutTextBody.length)];

Sample code for b) for substrings within the string is:

NSRange rangeDV = [holdString rangeOfString:@"DELUXE VERSION"];

Sample code for c) for substrings within the string is:

[aboutTextBody setAttributes:NWStyle range:rangeDV];

You can also set up paragraph styles in the same way for either the entire strings or substrings only:

NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.alignment = NSTextAlignmentCenter;
paraStyle.lineBreakMode = NSLineBreakByWordWrapping;

Edited to add: The way to add the paragraph style is slightly different:

[aboutTextBody addAttribute:NSParagraphStyleAttributeName value:paraStyle range:rangeDV];

Upvotes: 1

Related Questions