CocoaDev

Edit AllPages

I got annoyed that NSAlert doesn’t have any SIMPLE way to add a checkbox to it, so I wrote this custom subclass to add it in, enjoy:

NSAlertCheckbox.h:

#import <Cocoa/Cocoa.h>

// private methods @interface NSAlert (CheckboxAdditions)

@interface NSAlertCheckbox : NSAlert { NSButton *_checkbox; }

NSAlertCheckbox.m:

#import “NSAlertCheckbox.h”

@interface NSAlertCheckbox (Private)

@implementation NSAlertCheckbox

#pragma mark -

#pragma mark -

@implementation NSAlertCheckbox (Private)

Here’s some example code using it:

// prompt the user NSAlertCheckbox *alert = [NSAlertCheckbox alertWithMessageText:@”Install Flash” defaultButton:@”Download” alternateButton:@”No Thanks” otherButton:nil informativeText:@”The current verson of flash is out of date, do you wish to download the latest?”];

[alert setShowsCheckbox:YES]; [alert setCheckboxText:@”Don’t ask me again.”]; [alert setCheckboxState:NSOnState];

if ([alert runModal] == NSAlertDefaultReturn) { // go download flash }

if ([alert checkboxState] == NSOnState) { // go set a pref somewhere }

– TristanOTierney


I’ve got some similar code that will use the private checkbox methods built into NSAlert, if they’re available, or fallback to a regular checkbox if the code appears to be missing. The advantage to this code is that there is less direct manipulation of the alert’s window and controls–i.e. it’s a higher-level implementation. If people would like, I can clean it up and post it as a download. - JonathanGrynspan


TristanOTierney thanks and JonathanGrynspan, please do.


Looks like Leopard allows you not only to set an accessory view to the NSAlert but to set a “suppression checkbox”. - DanGrover