问题
I took a deep dive into TextKit and wondered how the editor placeholders are implemented in the Xcode code editor:
You can also try this yourself and type something along the lines of: <#Hello#>
, which automatically turns into a placeholder.
The Xcode editor is built with TextKit. After some research I came up with two possible strategies:
- Using
NSTextAttachment
: as soon as a string matching the placeholder pattern<#...#>
is detected, that string is removed and replaced by aNSTextAttachment
, which handles drawing the "badge-shaped" background and the text. - Using
NSLayoutManager
: not sure if this would work, but it could go like this:- The start and end markers (glyphs)
<#
+#>
are hidden (layoutManager(... shouldGenerateGlyphs, forGlyphRange...)
) - The layout manager handles drawing the badge background in
drawBackground(forGlyphRange glyphsToShow: NSRange, at origin: NSPoint)
- The start and end markers (glyphs)
I'd like to implement something similar and would appreciate any suggestions, as to which way to proceed.
来源:https://stackoverflow.com/questions/53415525/textkit-how-is-the-editor-placeholder-feature-implemented-in-xcode