macoscocoafocusxojo

How to draw a Cocoa focus ring without subclassing?


I'd like to draw a proper, modern animated focus ring around a control, which according to Q&A 1785, should be a simple matter of overriding the -drawFocusRingMask and -focusRingMaskBounds methods.

Trouble is, for this project I have to use Xojo, which can declare and invoke Cocoa methods, but doesn't give me any opportunity to actually create my own view subclass.

So, is there any way to get a proper focus ring without making an actual subclass? Some other methods, perhaps introduced after this 10.7 tech note, that get the job done? Or some sneaky way to inject a method into an existing class at runtime?


Solution

  • As one comment suggested, class_addMethod() would be right if you want to add an optional protocol method. The public macoslib project has some code that shows how to do that, just search for that name.

    However, if the function is already implemented, then you cannot add another. In that case method swizzling is the solution. It's a common method to replace a selector'd function address with another, and then call the original one.

    I don't seem to have an example in Xojo for that at hand, though.

    Update

    For standard Cocoa controls the simplest solution is to set the NSView property focusRingType accordingly (available in macoslib). Implementing drawFocusRingMask is only necessary for custom controls.