更改NSTextField的边框颜色

lar*_*230 9 cocoa objective-c nstextfield border-color

我想更改NSTextField对象的边框颜色,但我无法实现它.

我已经尝试了很多解决方案EX:是子类,画背景......

有没有人可以解决这个问题或分享任何想法?

请告诉我.非常感谢.

Par*_*fna 13

使用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];
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述

在此输入图像描述


Ji *_*ang 6

您可以尝试 CALayer,无需子类化

self.wantsLayer = true
self.layer?.borderColor = NSColor.red.cgColor
self.layer?.borderWidth = 1
Run Code Online (Sandbox Code Playgroud)