drawWithFrame: draws NSTextFieldCell background out of registration with frame

269 Views Asked by At

I'm failing to have a NSTextFieldCell created and drawn programmatically recreate the same visual appearance equivalently-configured NSTextFieldCells have when built in Interface Builder and drawn automatically by Cocoa.

Context is a custom NSView that displays content that user can select, delete or replace. Though this content is non-textual, I'd like the field to resemble an NSTextField, so I'm trying to press an NSTextFieldCell into service to draw a bezel, background fill, etc., that would match a corresponding NSTextField's.

I setup the cell as follows (during custom control init()):

textFieldCell = [[NSTextFieldCell alloc] init];
[textFieldCell setDrawsBackground: YES];
[textFieldCell setBackgroundColor: NSColor.blueColor];
[textFieldCell setBackgroundStyle: NSBackgroundStyleNormal];
[textFieldCell setBezeled: YES];
[textFieldCell setStringValue: @""];

and then in custom control's drawRect,

- (void) drawRect: (NSRect) rect
{
    // Draw an NSTextField-like background
    if( isSelectAndDeletable)
    {
         [textFieldCell drawWithFrame: [self bounds] inView: self];
    }
    ...  // more content drawing here
 }

This produces on onscreen 1-pixel frame of the appropriate thickness and size, and fills it with blue. But the frame itself is gray, not blue, and the fill touches the frame on top (no white margin) and misses it by two pixels at the bottom (thick white margin). By contrast, when I let Cocoa draw my textFieldCells either as part of an NSTextField or as standalone cells created in Interface Builder, the frame is drawn WITH the cell's background color and the fill is inset with one pixel white margin all around.

This picture demonstrates the problem. It shows three NSTextFieldCells, the second of which is (defectively) drawn by my own call to drawWithFrame:inView:, the other two (correctly) directly by the runtime.

Any ideas what I'm doing wrong? I feel like I am passing the proper rect (the frame is in the correct location), and the single call produces both the correct stroke (frame) and incorrect fill (background). Is this some misconfigured bezel effect? I can hand draw the effect I'm after but would rather stick with NSTextFieldCell if I can fix my approach here.

0

There are 0 best solutions below