Skip to content

Instantly share code, notes, and snippets.

@importRyan
Last active May 10, 2023 14:15
Show Gist options
  • Save importRyan/669999190f3b4db8e031c5971e7fa7ed to your computer and use it in GitHub Desktop.
Save importRyan/669999190f3b4db8e031c5971e7fa7ed to your computer and use it in GitHub Desktop.
Custom NSTextView Insertion Point

Custom NSTextView Insertion Point

While making the default insertion caret pop a little wider for better accessibility, I ran into an issue where the insertion point ghosted on arrow key presses. Christian Tietze observed the same issue.

My culprit was settings an x offset for the rect inside drawInsertionPoint. While Christian's blog code doesn't include an offset, there's otherwise no difference in our approach.

Below draws wider insertion caret with rounded corners.

class FatRoundInsertionCaretTextView: NSTextView {

    var caretWidth: CGFloat = 3
    var caretColor = NSColor.systemOrange
    
    private lazy var radius = caretWidth / 2
    private lazy var displayAdjustment = caretWidth - 1

        open override func drawInsertionPoint(in rect: NSRect, color: NSColor, turnedOn flag: Bool) {
            
            var rect = rect
            rect.size.width = caretWidth

            let path = NSBezierPath(roundedRect: rect,
                                    xRadius: radius,
                                    yRadius: radius)
            path.setClip()

            super.drawInsertionPoint(in: rect,
                                     color: caretColor,
                                     turnedOn: flag)
        }

        open override func setNeedsDisplay(_ rect: NSRect, avoidAdditionalLayout flag: Bool) {
            var rect = rect
            rect.size.width += displayAdjustment
            super.setNeedsDisplay(rect, avoidAdditionalLayout: flag)
        }
}
@yaosamo
Copy link

yaosamo commented Jan 10, 2022

thank you very much! This helped me with my small note taking app project :)

@vsameer
Copy link

vsameer commented May 10, 2023

Thank you 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment