Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Bold selected part of my string in a text view

I would like to make the part of the text that the user has selected to Helvetica Neue Bold. This is the code I have however it does not seem to do anything.

UITextRange *selectedRange = [textView selectedTextRange];

    NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
    NSString *yourString = textView.text;
    NSRange boldedRange = [textView textInRange:selectedRange];

    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];

    [attrString beginEditing];
    [attrString addAttribute:kCTFontAttributeName
                       value:boldFontName
                       range:boldedRange];

    [attrString endEditing];

1 Answer

Stone Preston
Stone Preston
42,016 Points

from the UITextView documentation on the font property:

font The font of the text.

@property(nonatomic, retain) UIFont *font Discussion This property applies to the entire text string. The default font is a 17-point Helvetica plain font.

In iOS 6 and later, assigning a new value to this property causes the new font to be applied to the entire contents of the text view. If you want to apply the font to only a portion of the text, you must create a new attributed string with the desired style information and assign it to the attributedText property.

so perhaps try assigning that string to the attributedText property:

 NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
    NSString *yourString = textView.text;
    NSRange boldedRange = [textView textInRange:selectedRange];

    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];

    [attrString beginEditing];
    [attrString addAttribute:kCTFontAttributeName
                       value:boldFontName
                       range:boldedRange];

    [attrString endEditing];

   texView.attributedText = attrString;

It is effecting the whole of the text in the textview rather than the selected range. Do you know why this could be?

Stone Preston
Stone Preston
42,016 Points

hmm you might check that your range is correct then