4ntoine 4ntoine - 11 days ago 5
iOS Question

NSAttributedString: underline is not applied

I'm trying to add underline style for

UITextView
and it's not applied. If i use "shadow" (uncomment shadow styling and comment underline styling) i can see it, but no underline is applied for some reason. I use "Courier New" font.

- (void) addDiagHighlighting: (NSMutableAttributedString*)attrString start:(int)start end:(int)end severity:(int)severity {
// ignore diags that are out of bounds
if (start > attrString.length || end > attrString.length)
return;

NSRange range = NSMakeRange(start, end - start);
UIColor *diagColor = [self getSeverityColor: severity];

// shadow
// NSShadow *shadow = [[NSShadow alloc] init];
// [shadow setShadowColor: diagColor];
// [shadow setShadowOffset: CGSizeMake (1.0, 1.0)];
// [shadow setShadowBlurRadius: 1.0];
// [attrString addAttribute:NSShadowAttributeName
// value:shadow
// range:range];

// underline
[attrString addAttributes:@{
NSUnderlineColorAttributeName : diagColor, // color
NSUnderlineStyleAttributeName : @(NSUnderlinePatternSolid) // style
}
range:range];
}


i can change adding attributes to adding both shadow and underling and i can see shadow but still no underline:

// shadow + underline
[attrString addAttributes:@{
NSShadowAttributeName : shadow, // shadow
NSUnderlineColorAttributeName : diagColor, // color
NSUnderlineStyleAttributeName : @(NSUnderlinePatternSolid) // style
}
range:range];

Answer

You need to OR a NSUnderlinePattern with an NSUnderlineStyle to get it working https://developer.apple.com/library/ios/documentation/uikit/reference/NSAttributedString_UIKit_Additions/index.html#//apple_ref/c/tdef/NSUnderlineStyle

Try this:

[attrString addAttributes:@{
                        NSShadowAttributeName : shadow, // shadow
                        NSUnderlineColorAttributeName : diagColor, // color
                        NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle | NSUnderlinePatternSolid) // style
                        }
               range:range];

Or with dots...

[attrString addAttributes:@{
                        NSShadowAttributeName : shadow, // shadow
                        NSUnderlineColorAttributeName : diagColor, // color
                        NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle | NSUnderlinePatternDot) // style
                        }
               range:range];
Comments