Question

I am a beginner learning iOS development.

I am trying to limit the contents of a label marked "Factor" to only allow 2 whole integers between 0 and 99. I also want to force the user to enter at least two digits for every Factor attempt (i.e. "7" would be "07").

The label is not directly edited by the user. There is a number pad that the user can use to enter the Factor directly (just as you would on a calculator or remote control). There is also an Increment and Decrement button that modifies the label text.

I have limited the label so that it will not go above 99 or below 0 when the Increment or decrement buttons are pushed. But I am stuck on how to limit the user from pressing 3 or more numbers and that getting populated in the label text.

Current behavior:
Currently, if I press '9','0','1', that will result in '901'.
My goal would be to press '9','0','1', and see '1'.
In other words, more than 2 characters would never be displayed and once a third number is pushed, it will overwrite the existing two.

Here is what I am doing for my number buttons:

- (IBAction)numPush:(UIButton *)sender {
NSString *number = sender.currentTitle;
if (self.numberCheck)
{        self.fDisp.text = [self.fDisp.text
                          stringByAppendingString:number];
}
else
{
    self.fDisp.text = number;
    self.numberCheck = YES;
}
}
Was it helpful?

Solution

I think is is easy to accomplish that. See my solution below, I think it should work in your case.

- (IBAction)numPush:(UIButton *)sender {
   NSString *number = sender.currentTitle;
   if([self.fDisp.text length] == 2)
    self.fDisp.text = sender.currentTitle;
   else 
    self.fDisp.text = [self.fDisp.text stringByAppendingString:number];

}

OTHER TIPS

You could simply check the length of the label string.

    if ([self.fDisp.text length] == 2)
      self.fDisp.text = sender.currentTitle;
   else
     self.fDisp.text = [self.fDisp.text
                          stringByAppendingString:number];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top