epetousis
epetousis

Reputation: 454

Using NSBackgroundStyleLowered on an NSButtonCell?

I use this snippet of code...

[[textField cell] setBackgroundStyle:NSBackgroundStyleLowered];

...to give a piece of text a shadow, and it works. When I try to do the same thing with a button:

[[refreshButton cell] setBackgroundStyle:NSBackgroundStyleLowered];

the code doesn't work. The button is a Momentary Change button with a white transparent circular arrow. Any ideas why this couldn't be working? It seems like it would work, since it is still a cell.

Upvotes: 2

Views: 224

Answers (1)

Thomas Zoechling
Thomas Zoechling

Reputation: 34263

NSCell subclasses have different drawing behaviors. So a settable background style doesn't mean that the style is actually used in the concrete subclass.

NSButtonCells use the interiorBackgroundStyle property before drawing the title. This property doesn't expose a setter, so you'd have to subclass NSButtonCell and set the cell class in Interface Builder accordingly.
To achieve the lowered background style, override interiorBackgroundStyle in your subclass:

- (NSBackgroundStyle)interiorBackgroundStyle
{
    return NSBackgroundStyleLowered;
}

If you need more control over the drawing, you could also override NSButtonCell's drawInteriorWithFrame:inView:.

A hacky approach (that doesn't require subclassing) would be to modify the attributed title string to achieve a similar effect:

NSShadow* shadow = [[NSShadow alloc] init];
[shadow setShadowOffset:NSMakeSize(0,-1)];
[shadow setShadowColor:[NSColor whiteColor]];
[shadow setShadowBlurRadius:0];
NSAttributedString* title = [button.cell attributedTitle];
NSMutableDictionary* attributes = [[title attributesAtIndex:0 longestEffectiveRange:NULL inRange:NSMakeRange(0, title.length)] mutableCopy];
[attributes setObject:shadow forKey:NSShadowAttributeName];
NSAttributedString* string = [[NSAttributedString alloc] initWithString:[button.cell title] attributes:attributes];
[button.cell setAttributedTitle:string];

Upvotes: 2

Related Questions