Assignment #1 Extra Task #1

Please note, this blog entry is from a previous course. You might want to check out the current one.

Implement a “backspace” button for the user to press if they hit the wrong digit button. This is not intended to be “undo,” so if they hit the wrong operation button, they are out of luck! It’s up to you to decided how to handle the case where they backspace away the entire number they are in the middle of entering, but having the display go completely blank is probably not very user-friendly.

Add a backspace button to the story board and connect it to an action function “backSpace”, which basically does nothing if the user is not in the middle of entering a number, otherwise removes the last digits from display and history or writes a zero to display if there is only one digit left:

- (IBAction)backSpace {
    if (!self.userIsInTheMiddleOfEnteringANumber) return;
    NSString *display = [self.display.text copy];
    NSString *history = [self.history.text copy];
    NSInteger lengthDisplay = [display length];
    NSInteger lengthHistory = [history length];
    if (lengthDisplay > 1) {
        self.display.text = [display substringToIndex:(lengthDisplay - 1)];
        self.history.text = [history substringToIndex:(lengthHistory - 1)];
    } else {
        self.display.text = @"0";
        self.history.text = [history substringToIndex:(lengthHistory - 2)];
        self.userIsInTheMiddleOfEnteringANumber = NO;
    }    
}

As this extra task does not agree with the chosen solution to prevent multiple “.” in the entered number, we remove all the occurrences where userIsInTheMiddleOfEnteringAFloat is set, and add an appropriate getter which looks for existing “.” in the display field:

- (BOOL)userIsInTheMiddleOfEnteringAFloat
{
    NSRange range = [self.display.text rangeOfString:@"."];
    if (range.location == NSNotFound) return NO;
    return YES;
}
FacebooktwitterredditpinterestlinkedintumblrmailFacebooktwitterredditpinterestlinkedintumblrmail

Leave a Reply

Your email address will not be published.