Haseena Parkar
Haseena Parkar

Reputation: 979

NSView Border Color

i am applying a border to NSView but how can i change the bordercolor. Using NSColor with setBorderColor is showing a warning. I want to use Orange Color in Border

    [self setWantsLayer:YES];
    self .layer.masksToBounds   = YES;    
    self.layer.borderWidth      = 6.0f ;

    [self.layer setBorderColor:CGColorGetConstantColor(kCGColorBlack)]; 

How can i set other colors(excluding black and white) in Border

Regards, Haseena

Upvotes: 8

Views: 11195

Answers (3)

Cliff Ribaudo
Cliff Ribaudo

Reputation: 9039

Wow... so simple these days. In your NSView when created:

self.wantsLayer = YES;
self.layer.borderWidth = 1;

Then in drawRect (so that you can respond to changes for dark mode or other Appearances) set the border color.... and DON'T Forget to use system colors that respond to Appearance changes or colors you define in Asset catalog that support all appearances you support.

-(void)drawRect:(NSRect)rect
{
    self.layer.borderColor = [NSColor systemGrayColor];
    // or color defined in Asset Catalog
    self.layer.borderColor = [NSColor colorNamed:@"BorderColor"].CGColor;
    [super drawRect:rect];
}

It's that simple.

Upvotes: 3

onmyway133
onmyway133

Reputation: 48085

You can use NSBox, which is a subclass of NSView and designed to handle these cases

let box = NSBox()
box.boxType = .custom
box.alphaValue = 1
box.borderColor = NSColor.red
box.borderType = .lineBorder
box.borderWidth = 4

Upvotes: 7

Jason Harwig
Jason Harwig

Reputation: 45551

You need to convert to a CGColorRef

NSColor *orangeColor = [NSColor orangeColor];

// Convert to CGColorRef
NSInteger numberOfComponents = [orangeColor numberOfComponents];
CGFloat components[numberOfComponents];
CGColorSpaceRef colorSpace = [[orangeColor colorSpace] CGColorSpace];    
[orangeColor getComponents:(CGFloat *)&components];    
CGColorRef orangeCGColor = CGColorCreate(colorSpace, components);

// Set border
self.view.layer.borderColor = orangeCGColor;

// Clean up
CGColorRelease(orangeCGColor);

Or if you can require 10.8+, use [aColor CGColor]

Upvotes: 7

Related Questions