How to implement a custom focus ring in drawRect for NSTextField or NSTextVew

I want to draw a custom focus ring for my subclass of NSTextView (which does not have a focus ring by default). I managed to implement it by overriding the parent NSScrollView drawRect and adding this code:

 - (void)drawRect:(NSRect)dirtyRect { if (focused) { NSSetFocusRingStyle(NSFocusRingOnly); NSRectFill(dirtyRect); } [super drawRect:dirtyRect]; } 

However, I want to draw my own custom focus ring. I searched and searched for examples of this, and tried to mess around and write it myself, to no avail. The biggest problem I am having is that it will be cropped in an NSScrollView / NSTextView , no matter how I do it.

Thanks.

+4
source share
1 answer

The Carbon framework has HIThemeBeginFocus() and HIThemeEndFocus() , which allow you to call any series of drawings (for example, a rectangle or shape) for an automatic "focused" appearance. Requires Mac OS X 10.5 or later.

It directly uses Core Graphics. To find the CG context from the drawRect: method in Cocoa, you should do something like:

 NSGraphicsContext* contextMgr = [NSGraphicsContext currentContext]; CGContextRef drawingContext = (CGContextRef)[contextMgr graphicsPort]; 

To avoid cropping, one option is to use a parent view (for example, an NSBox that has no border) to give an extra complement. Perform a custom drawing on an insert in the parent view that will not be cropped; in other words, give the illusion that the view is slightly smaller than its actual rectangle.

0
source

All Articles