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

Cameron Bradford
Cameron Bradford
227 Points

Help Creating a Button that Underlines text

Hi All,

I'm a novice and I'm trying to make a simple photo editing app that allows you to add text and to be able to bold, italicize, and underline it. I have it all working except the underline.

The code I have works, however, for it to work you have to highlight/select the text and then press underline. I'd like it to underline the text element without having to highlight/select it. Any ideas on how to get this code to do that?

Objective-C
-(void)underlineTextButton{
UITextView selectedText = (UITextView ) selectedElement;
NSRange range = selectedText.selectedRange;
NSTextStorage *textStorage = selectedText.textStorage;
[textStorage addAttribute: NSUnderlineStyleAttributeName
value:[NSNumber numberWithInt:NSUnderlineStyleSingle]
range:range];
}

2 Answers

Enara L. Otaegi
Enara L. Otaegi
13,107 Points

I've never used this but it seems to me that the solution could be passing the length of the text instead of the selectedRange. Try this:

NSRange range = NSMakeRange(0, selectedText.text.length);
Cameron Bradford
Cameron Bradford
227 Points

Thank you so much for your response. I'll let you know how it goes!