Change border color of NSTextField

孤人 提交于 2019-12-03 17:39:09

问题


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.


回答1:


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:




回答2:


You can try CALayer without the need for subclassing

self.wantsLayer = true
self.layer?.borderColor = NSColor.red.cgColor
self.layer?.borderWidth = 1



回答3:


For me Parag's answer resulted in some strange textfield drawing, so I ended up with this simple code (based on his answer):

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    if (!self.borderColor) {
        return;
    }

    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];
    [self.borderColor set];
    [path stroke];
}


来源:https://stackoverflow.com/questions/18568054/change-border-color-of-nstextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!