Steven Hovater
Steven Hovater

Reputation: 1419

Can I get an Checkbox to visually change its state before sending its action?

I have an OS X app with two checkboxes (NSButton). If the first(primary) is unchecked, it disables and unchecks the second one.

Here is the code for that functionality,

@IBAction func peopleCheckboxAction(sender: AnyObject) {
    if(self.peopleCheckbox.state == NSOffState){
        self.peopleCommentsCheckbox.enabled = false
        self.peopleCommentsCheckbox.state = NSOffState

    }else{
    self.peopleCommentsCheckbox.enabled = true}

}

But here's the thing: that code gets executed before the first checkbox's state is changed, and it create a two-step action that feels almost like the first box is being unresponsive, or perhaps the user has clicked the wrong button, since the second control changes first. It's only a beat off, but I'd like to fix it.

Is there a simple way to reverse the way these two things are executed, or to ensure that they're happening nearly simultaneously?

Upvotes: 0

Views: 132

Answers (2)

geowar
geowar

Reputation: 4447

Try this: [self.peopleCheckBox sendActionOn:NSLeftMouseDownMask]; (The default behavior is the action is sent on mouse up.)

Upvotes: 1

Paul Patterson
Paul Patterson

Reputation: 6918

You could see what kind of effect you get with bindings - which would mean doing away with the action method altogether.

You'd normally set it all up in Interface Builder (IB), but copying and pasting the code below will quickly let you see if this approach is responsive enough for your needs. If it is, you should probably make the effort to set it all up in IB, leaving you with just the peopleState property in code.

#import "AppDelegate.h"

@interface AppDelegate ()

@property (weak) IBOutlet NSButton *peopleCheckBox;
@property (weak) IBOutlet NSButton *commentCheckBox;

@property NSNumber *peopleState;

@property (weak) IBOutlet NSWindow *window;

@end

@implementation AppDelegate


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    // Each time you click on the peopleState checkbox,
    // the value of the property <peopleState> will change.
    [self.peopleCheckBox bind:@"value"
                     toObject:self
                  withKeyPath:@"peopleState"
                      options:nil];

    // Each time the value of the property <peopleState> changes,
    // the 'enabled' status of the commentCheckBox is updated
    // peopleState == NSOffState -> commentCheckBox disabled.
    [self.commentCheckBox bind:@"enabled"
                      toObject:self
                   withKeyPath:@"peopleState"
                       options:nil];
}



@end

Upvotes: 0

Related Questions