How to do this?!

Trip

Registered
I'm trying to do something somewhat like this:

- (IBAction)button9Pressed:(id)sender
{
[textInput setFloatValue:textInput floatValue"+9"];
}

Basically what's going on here is the user is going to push a button, and then the program will take a NSTextField (textInput in this case) and take the text that's already in the field and add 9 onto it. But I don't know how to do that! Can anybody help me?!

e.x.: the NSTextField says: "We have..." and then a user pushes a button and I want the NSTextField to add "9" onto the current text and state: "We have...9". Get it? HELP! :D
 
This code is not tested, just written from memory, but it should do the trick:


Code:
// this method is invoked whenever a button is pressed
// not only when "9" is pressed
- (IBAction)buttonPressed:(id)sender { 
    // here we should determine which button was pressed
    // assume sender is of type NSButton, otherwise this will crash
    // assume that the title of the button is a number
    int increment = [[sender title] intValue];
    

    // we have already saved the current count in the
    // variable "count" of type int
    count += increment;


    [textInput setStringValue:[NSString stringWithFormat:@"We have %d", count]];

    // we're done.

}

The code above assumes two things: that you have an instance variable that contains the number to be incremented and displayed, and that the buttons have titles that are numbers and not strings (i.e "9" not "nine" or "number 9"), if that is not true, you'll have to rewrite the code that identifies the button.

You need only one method, regardless of how many buttons there are, just check in the method for which button was pressed and use that value.

It could be solved by checking which number was currently displayed and incrementing that, but it would be much more complicated and unneccessary.

theo
 
Back
Top