Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to underline part of string with NSAttributedString objective-c

Underling a string only works when the range starts from zero. If i start it at 1 then it works. The green colour works regardless.

+ (NSAttributedString*)returnNSAttributedString:(NSString*)string range:(NSRange)range WithColour:(UIColor*)colour WithUnderLine:(BOOL)underline {
    NSMutableAttributedString *attributedString =
    [[NSMutableAttributedString alloc] initWithString:string];
    if (underline) {
        [attributedString addAttributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)} range:range];
    }
    [attributedString addAttribute:NSForegroundColorAttributeName value:colour range:range];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSRangeFromString(string)];
    return attributedString;
}

it works on iOS 7 not iOS 8.

like image 323
user1898829 Avatar asked Dec 19 '22 10:12

user1898829


1 Answers

You can use the NSUnderlineStyleAttributeName and NSUnderlineColorAttributeName attributes. You can use it like this:

NSRange foundRange = [wordString rangeOfString:@"Base Mix"];
if (foundRange.location != NSNotFound)
{
    [wordString beginEditing];
    [wordString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:1] range:foundRange];
    [wordString addAttribute:NSUnderlineColorAttributeName value:[NSColor redColor] range:foundRange];
    [wordString endEditing];
}
like image 166
Shubhendu Avatar answered Dec 24 '22 03:12

Shubhendu