开发者

Newbie to iPhone SDK. How can I insert text into a UILabel without 'setText'...?

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 stu开发者_运维问答ff. 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!


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"]];


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.


@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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜