Question

Is there a way to get the position where the text in an NSTextFieldCell will be drawn when you call [super drawInteriorWithFrame:cellFrame inView:controlView] in drawInteriorWithFrame:inView: ?

Was it helpful?

Solution

The text rectangle is the return value of titleRectForBounds: passed cellFrame with mysterious 2px horizontal inset:

// this code ...
NSRect bounds = NSInsetRect(cellFrame, 2, 0); // dont ask me why
NSRect titleRect = [self titleRectForBounds:bounds];
[self.attributedStringValue drawInRect:titleRect];

// ... is equivalent to
[super drawInteriorWithFrame:cellFrame inView:controlView];

I don't know for sure what those 2px stand for, it's been figured out experimentally by trying all operating systems from 10.6 to 10.9-preview with all possible text field configurations. It seems there is always this unconditional 2px inset. One can easily confirm the default implementation does call NSInsetRect with exactly those parameters by setting a breakpoint and looking into debugger disassembly.

My guess: the 2px inset is needed to avoid clipping when starting or stopping letter sticks out of bounds for sake of better typography (zoom in and look closely where W or A letters are really rendered compared to say H or P).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top