Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customizing a NSButtonCell with images and highlighting

Tags:

macos

cocoa

I want to create a custom switch for my application, in which I supply three images for the possible states (on, off, mousedown). The whole appearance is contained in the images, so I do not want Cocoa to highlight (darken) the button by itself during mousedown.

At the moment, I have created a NSButtonCell subclass, dragged a bevel button of NSButtonTypeMomentaryChange into my view and custom set the button cell class type to my subclass. The subclass just implements awakeFromNib to try and set some desired behavior:

- (void)awakeFromNib
{
    [self setShowsStateBy:NSContentsCellMask];
    [self setHighlightsBy:NSContentsCellMask];
}

which I thought (according to the documentation) would disable the mousedown-darkening of the button. It does not.

This is where I stand and now I have two questions:

  • How can I set the ButtonCell class to just show my prepared picture on mousedown and do not darken / draw borders around the button?
  • What would be the cleanest/most proper way to implement the other behavior of a switch, i.e. showing the off/on position depending on the previous state and being able to communicate its state properly to other objects?
like image 380
mss Avatar asked Aug 05 '11 13:08

mss


1 Answers

Set your button's type to On/Off. Subclass its cell. Write this two methods:

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
    if ([self state])
    {
        [onStateImage drawInRect:cellFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
    }
    else
    {
        [offStateImage drawInRect:cellFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
    }
} 
- (void)highlight:(BOOL)flag withFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
    if (flag){
        [downStateImage drawInRect:cellFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];

    }
}
like image 83
unknown Avatar answered Sep 30 '22 14:09

unknown