I’d like to have an NSButton
with an image and an alternate image. The alternate image should be displayed while the button is being pressed and I’d also like to display the alternate image from code, calling something like [button setSelected:YES]
. Is this possible without monkeing with the alternateImage
property by hand?
Asked
Active
Viewed 6,998 times
8

zoul
- 102,279
- 44
- 260
- 354
4 Answers
19
This is possible without manually changing the button's image:
In Interface Builder (xib/nib Editor) set the Type of NSButton to "Toggle" and the image will automatically change to the alternate image/title.

auco
- 9,329
- 4
- 47
- 54
6
You can use a NSButton
with type set to NSToggleButton
and then switch between the image
and the alternateImage
using the NSOnState
/ NSOffState
states of the NSButton
.
NSButton* theButton = [[NSButton alloc] initWithFrame:....];
theButton.image = .....
theButton.alternateImage = .....
theButton.state = NSOffState; // displays the image
theButton.state = NSOnState; // displays the alternateImage

yonel
- 7,855
- 2
- 44
- 51
3
The easiest way is to switch between the two images:
@implementation NSButton (Select)
- (void) setSelected: (BOOL) yn
{
NSImage *const tmp = [self image];
[self setImage:[self alternateImage]];
[self setAlternateImage:tmp];
}
@end
-
Thanks, you’re probably right. I’ve added a simple category to switch between the images. – zoul Mar 17 '11 at 07:55
-
Any idea how I can set the alternate image for the hover event (when the mouse is over the button, not when clicked)? – ThE uSeFuL Oct 21 '11 at 04:56
-
@ThEuSeFuL : you have to use a `trackingArea` for the button, and if your button type is `NSToggleButton`you can switch between the standard and alternate images using `theButton.state = NSOffState;` and `theButton.state = NSOnState;`` – yonel Sep 30 '14 at 11:36
1
I just built all 10 types of buttons in the interface editor's attribute inspector with no added coding. Here are the results:
button type | while held down | when released |
---|---|---|
Momentary Push-In | first image darkened | first image |
Momentary Light | first image darkened | first image |
Momentary Change | ALT IMAGE | first image |
Push On / Push Off | first image darkened | first image |
On / Off | first image darkened | first image |
Toggle | ALT IMAGE | ALT IMAGE |
Switch | ALT IMAGE | ALT IMAGE |
Radio (not valid) | ||
Accelerator | first image darkened | first image |
Multi Level Acc. | first image darkened | first image |
Toggle and Switch will revert to the original image when pressed again. (If you change the button type to Radio in the button's Attribute Inspector, it reverts to Switch.)

Pierre Dufresne
- 166
- 1
- 6