Say I have an NSTextView
(or a UITextView
on iOS) and I want the user to be able to insert horizontal divider rules, like the HTML
I remember trying to do this years ago. Using NSTextAttachment was the method that worked for me. I bookmarked this conversation with Mike Ferris to help me remember how to do it. I don't have the code anymore, but it was pretty straightforward. I subclassed NSTextAttachmentCell
which conforms to NSTextAttachmentCellProtocol
. You override cellFrame(for textContainer: NSTextContainer, proposedLineFragment lineFrag: NSRect, glyphPosition position: NSPoint, characterIndex charIndex: Int)
which gives you access to its container that can provide its width, and it has the line fragment which gives you the y position of the text above your divider (plus any padding you want). Then just override the draw(withFrame cellFrame: NSRect, in controlView: NSView?)
method and draw your divider.
As for the payload NSData, you could do anything with that. Maybe you include the width of the line, it's padding, color, etc? The good thing about using NSTextAttachment is that it stays embedded in the text itself like the
tag.