Using TextKit to underline text is accomplished using a method similar to any one of the methods shown in the preceding code, with some modifications. Here is a code sample:
NSDictionary *currentAttributesDict = [self.textView.textStorage attributesAtIndex:0 effectiveRange:nil]; NSDictionary *dict; if ([currentAttributesDict objectForKey:NSUnderlineStyleAttributeName] == nil || [[currentAttributesDict objectForKey:NSUnderlineStyleAttributeName] intValue] == 0) { dict = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInt:1]}; } else{ dict = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInt:0]}; } [_textView.textStorage setAttributes:dict range:NSMakeRange(0, self.textView.text.length)];
Here we must check if the NSUnderlineStyleAttributeName
attribute already exists in our current text attributes. From here, we simply turn the underline attribute On or Off and apply it to our text.