Search code examples
iosbuttoncalculatorbackspace

Delete Button Calculator *Help*


I have this code for my calculator that lets me delete one number at a time!

- (IBAction)deleteButton:(id)sender {
    NSString *string = [Screen text];
    int length = [string length];
    NSString *temp = [string substringToIndex:length-1];

    if ([temp length] == 0) {
        temp = @"0";
    }
    [Screen setText:temp];
}

It works, but whenever I enter another number, it resets back to the whole thing, so lets take this as an example.

I have the number 5678, (I deleted 678), So my new number is 5, (Now if I press another number), it goes back to 56781 ( 1 being the new number)

Heres my full code for my project! ---> http://txt.do/oduh


Solution

  • As seen in your code, you are using SelectNumber to store value everywhere, but in deleteButton method you are not storing new value in SelectNumber. So you need to set the new value in deleteButton.

    - (IBAction)deleteButton:(id)sender {
        NSString *string = [Screen text];
        int length = [string length];
        NSString *temp = [string substringToIndex:length-1];
    
        if ([temp length] == 0) {
            temp = @"0";
        }
        SelectNumber = [temp intValue]; // set new value here
        [Screen setText:temp];
    }