Sean Herman
Sean Herman

Reputation: 313

Programmatically and automatically adding an integer into a UILabel? Possible?

I've set up a simple if statement that says if the input length is equal to 3 make the next character a "-".

It works well, but I'd like the "-" to automatically be put there after I press my button for the 3rd time. So I press, "1", "2", then when I press the "3" it automatically puts a "-" directly afterwards. Currently the "-" only gets placed when I hit the button for the 4th time?

-(IBAction)buttonDigitPressed:(id)sender {

    NSString *val = phoneNumberLabel.text;
    int length = [val length];

    } else {
        NSString *tagValue = [NSString stringWithFormat:@"%d", [sender tag]];
        phoneNumberLabel.text = [val stringByAppendingString: tagValue];

        if (length == 3) {
            phoneNumberLabel.text = [val stringByAppendingString:@"-"];

        }

        if (length == 7) {
            phoneNumberLabel.text = [val stringByAppendingString:@"-"];
        }

    }

}

Any help would be appreciated, greatly! Thanks!

Upvotes: 1

Views: 173

Answers (5)

Craig Williams
Craig Williams

Reputation: 418

-(IBAction)buttonDigitPressed:(id)sender {

  NSString *val = phoneNumberLabel.text;
  NSString *newValue = @"";
  NSString *dash = @"";

  int length = [val length];

  if ( ((length == 3) || (length == 7)) ) {
    dash = @"-";
  }

  newValue = [NSString stringWithFormat:@"%@%@%d", val, dash, [sender tag]];
  phoneNumberLabel.text = newValue;
}

Upvotes: 1

Prince Kumar Sharma
Prince Kumar Sharma

Reputation: 12641

Try this method,hope it will help you. Keep UILabel object blank in xib.

- (IBAction)pressAction:(UIButton*)sender
{
    if (lbl.text.length<=2) {
        lbl.text=[lbl.text stringByAppendingFormat:@"%i",sender.tag];
    }

    if (lbl.text.length>=3){
        lbl.text=[lbl.text stringByAppendingString:@"-"];
    }
}

Upvotes: 0

Prajwal Udupa
Prajwal Udupa

Reputation: 860

You can send the button the events. like [button sendActionsForControlEvents:UIControlEventTouchUpInside] Or even perform selector after delay may do the trick for you. both the cases you need not press a button

For the addition of "-" just check how many characters have been entered and when the third character has been entered add the "-".

Upvotes: -1

Girish
Girish

Reputation: 4712

Add the following code in buttonClicked method

if ([myLabel.text length] == 3)
{ 
   myLabel.text = [val stringByAppendingString:@"-"]; 
}

Upvotes: 1

sosborn
sosborn

Reputation: 14694

Just add that code in the same method after you update the label with the integer.

Upvotes: 0

Related Questions