Search code examples
nstextfieldnstextfieldcell

NSTextFieldCell draws white background only when not the first responder


I have two NSTextFields in a storyboard, both remain untouched from the default configuration, except I have changed their classes to a subclass. I've also subclassed the inner NSTextFieldCell. I've customized each as desired - pretty simple subclasses. The text field that is the first responder appears as expected, but the other text field does not. It is drawing a white background for its cell. Toggling between the two fields toggles the background. How can I remove this white background from the cell?

LoginTextField:

- (void)baseInit {
    self.drawsBackground = NO;
    self.wantsLayer = YES;
    self.backgroundColor = [[NSColor whiteColor] colorWithAlphaComponent:0.75];
    self.textColor = [NSColor blackColor];

    CALayer *layer = [[CALayer alloc] init];
    layer.backgroundColor = self.backgroundColor.CGColor;
    layer.borderWidth = 0;
    layer.cornerRadius = 6;

    self.layer = layer;
}

LoginTextFieldCell:

- (void)baseInit {
    self.drawsBackground = NO;
    self.focusRingType = NSFocusRingTypeNone;
}

enter image description here

If I override this function, the white background disappears, but so does the placeholder and text labels when not the first responder.

- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
    return [super drawInteriorWithFrame:cellFrame inView:controlView];
}

enter image description here

I'm developing the app in Xcode 7, running on OS X El Capitan.


Solution

  • For anyone who also saw this problem, the solution that worked for me was to set bordered to NO and configure self.layer instead of creating a new CALayer.

    LoginTextField:

    - (void)baseInit {
        self.drawsBackground = NO;
        self.wantsLayer = YES;
        self.textColor = [NSColor blackColor];
        self.bordered = NO;
    
        self.layer.backgroundColor = [[NSColor whiteColor] colorWithAlphaComponent:0.75].CGColor;
        self.layer.borderWidth = 0;
        self.layer.cornerRadius = 6;
    }