0

Okay, so I have a basic application and I built a custom numeric keyboard using some buttons. I have a button, for example 1, and a UILabel above. I got it to where when you click the button 1, it sets the text of the label to 1. Pretty simple stuff. But I need to add multiple characters and it's not letting me do so. Something like addText or insertText but addText isn't even a Cocoa method and insertText isn't what I'm looking for. Any help? Sorry for the newbie question. Thanks!

Alex Moore
  • 11
  • 4

3 Answers3

2

If what you’re looking for is a way to append a character to the end of the label’s string, do something like this:

[myLabel setText:[[myLabel text] stringByAppendingString:@"1"]];
Jeff Kelley
  • 19,021
  • 6
  • 70
  • 80
  • That worked perfectly! Thanks. Now this is a little trickier but the UIField is a price, and I want to automatically add a decimal place the the field as the number increments it's value. For example, when I type '1' the field would be something like 0.01, then if I hit '2' it'd be 0.12, then if I hit three it would look like 1.23. Any ideas? Thanks for your fast help! :) – Alex Moore Jan 27 '11 at 04:39
  • Alex, this sounds like a separate query and you would quite likely get better responses posting it as a new question – ccjensen Jan 27 '11 at 06:51
  • Separate question really but, I asked this question 2 years ago and there are quite a few approaches: – Meltemi Jan 27 '11 at 06:53
1

A UILabel's text property is an NSString. You should look over the NSString documentation to see what all is possible. The methods stringByAppendingString, stringByAppendingFormat, and stringWithFormat look like they might be useful for your problem.

pwc
  • 7,043
  • 3
  • 29
  • 32
0

@Jeff Kelley answered your question about appending text to a UILabel. With regards to your follow-up comment about the price:

If the user is entering numeric values into a UITextField, the delegate should respond to the -textField:shouldChangeCharactersInRange:replacementString: method. An example of what you might do is:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSNumberFormatter *fmt = [[[NSNumberFormatter alloc] init] autorelease];
    [fmt setGeneratesDecimalNumbers:YES];

    NSDecimalNumber *newCentValue = [[fmt numberFromString:string] decimalNumberByMultiplyingByPowerOf10:-2];
    // "price" is an instance, global, static, whatever.. NSDecimalNumber object
    NSDecimalNumber *newPrice = [[price decimalNumberByMultiplyingByPowerOf10:1] decimalNumberByAdding:newCentValue];

    NSString *labelText = [fmt stringFromNumber:newPrice];
    // do something with new label
}

Note that this method does not deal with the user wanting to remove a digit, etc.

Community
  • 1
  • 1
Aidan Steele
  • 10,999
  • 6
  • 38
  • 59