How to underline part of a string using NSAttributedString objective-c

String trimming is only performed when the range starts from zero. If I start it with 1, then it will work. Green color works independently.

+ (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.

+4
source share
2 answers

You can use the NSUnderlineStyleAttributeName and NSUnderlineColorAttributeName attributes. You can use it as follows:

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];
}
+10
source

Swift:

A small method. Gets a string and returns an NSMutableAttributedString with an underscore attribute over the full length of the string.

func getUnderlinedAttributedString(string string: String) -> NSMutableAttributedString
{
    let attributedString = NSMutableAttributedString.init(string: string)
    let stringRange = NSMakeRange(0, attributedString.length)

    attributedString.beginEditing()
    attributedString.addAttribute(NSUnderlineStyleAttributeName, value: 1, range: stringRange)
    attributedString.endEditing()

    return attributedString
}
+1
source

All Articles