Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change border color of NSTextField

I want to change the border color of NSTextField object, but I can't achieve it.

I already have tried many solutions EX: be subclass, draw background...

is there anyone who can resolve this issue or share any ideas?

Please let me know. Many thanks.

like image 970
larry761230 Avatar asked Sep 02 '13 07:09

larry761230


2 Answers

Use NSBezierPath

- (void)drawRect:(NSRect)dirtyRect
{
    NSPoint origin = { 0.0,0.0 };
    NSRect rect;
    rect.origin = origin;
    rect.size.width  = [self bounds].size.width;
    rect.size.height = [self bounds].size.height;

    NSBezierPath * path;
    path = [NSBezierPath bezierPathWithRect:rect];
    [path setLineWidth:2];
    [[NSColor colorWithCalibratedWhite:1.0 alpha:0.394] set];
    [path fill];
    [[NSColor redColor] set]; 
    [path stroke];

    if (([[self window] firstResponder] == [self currentEditor]) && [NSApp isActive])
    {   
        [NSGraphicsContext saveGraphicsState];
        NSSetFocusRingStyle(NSFocusRingOnly);
        [path fill]; 
        [NSGraphicsContext restoreGraphicsState];
    }
    else
    {
        [[self attributedStringValue] drawInRect:rect];
    }
}

Output:

enter image description here

enter image description here

like image 148
Parag Bafna Avatar answered Nov 17 '22 08:11

Parag Bafna


You can try CALayer without the need for subclassing

self.wantsLayer = true
self.layer?.borderColor = NSColor.red.cgColor
self.layer?.borderWidth = 1
like image 41
Ji Fang Avatar answered Nov 17 '22 10:11

Ji Fang