Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSView Border Color

Tags:

cocoa

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

like image 772
Haseena Parkar Avatar asked Jun 26 '12 14:06

Haseena Parkar


3 Answers

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]

like image 188
Jason Harwig Avatar answered Nov 12 '22 22:11

Jason Harwig


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
like image 28
onmyway133 Avatar answered Nov 12 '22 21:11

onmyway133


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.

like image 1
Cliff Ribaudo Avatar answered Nov 12 '22 22:11

Cliff Ribaudo