我一直在使用setBackgroundColor方法来更改NSButton的颜色,但我的问题是,除了这个之外,是否还有其他方法可以用来更改NSButton的颜色?
发布于 2013-05-06 15:44:45
要更改颜色或访问按钮所需的NSButton,通常需要使用IBOutlet,除非按钮是TableView / CollectionView等格式。
假设按钮插座是myButton,那么您需要
[[myButton cell] setBackgroundColor:[NSColor redColor]]; //Change the color according to your need编辑:
您也可以通过使用以下方法对NSButtonCell进行子类化来实现此目的
- (void)drawBezelWithFrame:(NSRect)frame inView:(NSView *)controlView
{
NSGraphicsContext* ctx = [NSGraphicsContext currentContext];
// corner radius
CGFloat roundedRadius = 17.0f;
NSColor *color = [NSColor redColor];
// Draw darker overlay if button is pressed
if([self isHighlighted]) {
[ctx saveGraphicsState];
[[NSBezierPath bezierPathWithRoundedRect:frame
xRadius:roundedRadius
yRadius:roundedRadius] setClip];
[[color darkenColorByValue:0.12f] setFill];
NSRectFillUsingOperation(frame, NSCompositeSourceOver);
[ctx restoreGraphicsState];
return;
}
// create background color
[ctx saveGraphicsState];
[[NSBezierPath bezierPathWithRoundedRect:frame
xRadius:roundedRadius
yRadius:roundedRadius] setClip];
[[color darkenColorByValue:0.12f] setFill];
NSRectFillUsingOperation(frame, NSCompositeSourceOver);
[ctx restoreGraphicsState];
//draw inner button area
[ctx saveGraphicsState];
NSBezierPath* bgPath = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(frame, 1.0f, 1.0f) xRadius:roundedRadius yRadius:roundedRadius];
[bgPath setClip];
NSColor* topColor = [color lightenColorByValue:0.12f];
// gradient for inner portion of button
NSGradient* bgGradient = [[NSGradient alloc] initWithColorsAndLocations:
topColor, 0.0f,
color, 1.0f,
nil];
[bgGradient drawInRect:[bgPath bounds] angle:90.0f];
[ctx restoreGraphicsState];
}
- (NSRect) drawTitle:(NSAttributedString *)title withFrame:(NSRect)frame inView:(NSView *)controlView {
NSGraphicsContext* ctx = [NSGraphicsContext currentContext];
[ctx saveGraphicsState];
NSMutableAttributedString *attrString = [title mutableCopy];
[attrString beginEditing];
NSColor *titleColor;
if ([[self getColorForButtonType] isLightColor]) {
titleColor = [NSColor blackColor];
} else {
titleColor = [NSColor whiteColor];
}
[attrString addAttribute:NSForegroundColorAttributeName value:titleColor range:NSMakeRange(0, [[self title] length])];
[attrString endEditing];
NSRect r = [super drawTitle:attrString withFrame:frame inView:controlView];
[ctx restoreGraphicsState];
return r;
}发布于 2015-05-07 19:18:25
我不知道这里发生了什么,但以下内容对我来说是有效的:
[[myButton cell] setBackgroundColor:[NSColor redColor]];但前提是我在NSButtonCell子类中重写了下面的方法:
- (void)drawBezelWithFrame:(NSRect)frame inView:(NSView *)controlView
{
[super drawBezelWithFrame:frame inView:controlView];
}有趣的事实是:它甚至没有被调用(用调试器测试)。
https://stackoverflow.com/questions/6904250
复制相似问题