views:

124

answers:

3

how should i take NSButton text value , e.g if i use 2 buttons with text Click and Cancel, i want to check which button is clicked and then show a message with NSRunAlertPanel(...) which button i have clicked..what code should i write for it when the button is clicked.

A: 

In you action method you get an argument, usually named 'sender', which is the button. So you could do something like:

- (IBAction)buttonClicked:(id)sender
{
    if ([[sender title] isEqualToString:@"Click"]) {
        NSLog(@"Click clicked.");
    } else if ([[sender title] isEqualToString:@"Cancel"]) {
        NSLog(@"Cancel clicked.");
    }
}

It's better not to use the title for checking the button, since the title could change in different localizations. You could specify the tag instead, which is simply an int and which can be used to identify different senders.

Nikolai Ruhe
thanks, it helped me. i will try to check it with the tag as well.
maddy
+1  A: 

The way this is typically implemented is that each button would call a different action, thus there would be no need to check the text of the button. See The Target-Action Mechanism.

In general it is almost always a bad idea to use the user visible text to control program logic because that makes localization harder.

You might also want to describe your situation further. Are you using Interface Builder to create your interface? Are these buttons in a modal dialog or a document window?

Jon Steinmetz
okay, i understand your point. I was just trying to try if i could do that, with a modal dialog , yes i used interface builder. thanks for the pointer.. :)
maddy
A: 

You could give the button a name in the class info tab of the inspector window in Interface Builder, then declare it as an IBOutlet in your app delegate.

AppDelegate.h:

IBOutlet    NSButton  *ClickButton;
IBOutlet    NSButton  *CancelButton;

Then hook up the outlet in Interface Builder, and just check to see which button is the sender in your method:

- (IBAction)buttonClicked:(id)sender
{
    if (sender == ClickButton) {
        NSLog(@"Click clicked.");
    }
    else {
        NSLog(@"Cancel clicked.");
    }
}
alesplin