I'm trying to add a dotted underline style to an NSAttributedString
(on iOS7+/TextKit). Of course, I tried the built-in NSUnderlinePatternDot
:
NSString *string = self.label.text;
NSRange underlineRange = [string rangeOfString:@"consetetur sadipscing elitr"];
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:string];
[attString addAttributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle | NSUnderlinePatternDot)} range:underlineRange];
self.label.attributedText = attString;
However, the style produced by this is actually rather dashed than dotted:
Am I missing something obvious here (NSUnderlinePatternReallyDotted
? ;) ) or is there perhaps a way to customize the line-dot-pattern?
I've spent a little bit of time playing around with Text Kit to get this and other similar scenarios to work. The actual Text Kit solution for this problem is to subclass NSLayoutManager
and override drawUnderline(forGlyphRange:underlineType:baselineOffset:lineFragmentRect:lineFragmentGlyphRange:containerOrigin:)
This is the method that gets called to actually draw the underline that is requested by the attributes in the NSTextStorage
. Here's a description of the parameters that get passed in:
glyphRange
the index of the first glyph and the number of following glyphs to be underlinedunderlineType
the NSUnderlineStyle
value of the NSUnderlineAttributeName
attributebaselineOffset
the distance between the bottom of the bounding box and the baseline offset for the glyphs in the provided rangelineFragmentRect
the rectangle that encloses the entire line that contains glyphRange
lineFragmentGlyphRange
the glyph range that makes up the entire line that contains glyphRange
containerOrigin
the offset of the container within the text view to which it belongsSteps to draw underline:
NSTextContainer
that contains glyphRange
using NSLayoutManager.textContainer(forGlyphAt:effectiveRange:)
.glyphRange
using NSLayoutManager.boundingRect(forGlyphRange:in:)
CGRect.offsetBy(dx:dy:)
baselineOffset
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With