Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTextField with rounded corners?

I'm trying to draw rounded corners around an NSTextField.

I've subclassed NSTextField, tried the code below, but without any result...

Any ideas?

- (void)drawRect:(NSRect)dirtyRect
{

    // black outline
    NSRect blackOutlineFrame = NSMakeRect(0.0, 0.0, [self bounds].size.width, [self bounds].size.height-1.0);
    NSGradient *gradient = nil;
    if ([NSApp isActive]) {
        gradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedWhite:0.24 alpha:1.0] endingColor:[NSColor colorWithCalibratedWhite:0.374 alpha:1.0]];
    }
    else {
        gradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedWhite:0.55 alpha:1.0] endingColor:[NSColor colorWithCalibratedWhite:0.558 alpha:1.0]];
    }
    [gradient drawInBezierPath:[NSBezierPath bezierPathWithRoundedRect:blackOutlineFrame xRadius:5 yRadius:5] angle:90];

}
like image 550
Dr.Kameleon Avatar asked Dec 05 '22 17:12

Dr.Kameleon


1 Answers

It is better to subclass NSTextFieldCell to draw rounded corners to preserve NSTextField functionality, e.g:

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
    NSBezierPath *betterBounds = [NSBezierPath bezierPathWithRoundedRect:cellFrame xRadius:CORNER_RADIUS yRadius:CORNER_RADIUS];
    [betterBounds addClip];
    [super drawWithFrame:cellFrame inView:controlView];
    if (self.isBezeled) {
        [betterBounds setLineWidth:2];
        [[NSColor colorWithCalibratedRed:0.510 green:0.643 blue:0.804 alpha:1] setStroke];
        [betterBounds stroke];
    }
}

Yields a nice rounded text field that works perfectly (if you had set it to draw a rectangle bezel in the first place, at least):

enter image description here

like image 193
Vervious Avatar answered Dec 20 '22 15:12

Vervious