开发者

formatting textfield while user is typing

开发者 https://www.devze.com 2023-02-14 07:13 出处:网络
I would like the user to type an amount in a textfield and I want the value to be formatted as it is being typed. Which means as the user types 开发者_运维知识库in the 4th digit, a comma appears at th

I would like the user to type an amount in a textfield and I want the value to be formatted as it is being typed. Which means as the user types 开发者_运维知识库in the 4th digit, a comma appears at the appropriate spot denoting the thousands. example: 3,450

Right now,I am trying to use the textfield delegate method "shouldChangeCharactersInRange" and NSNumberFormatter. Unfortunately I haven't had any success. Could someone point me in the right direction? thank you!


One option is to overlay a UILabel with a transparent background on top of your UITextField. Register as the delegate of the UITextField and implement:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

Then every time the user types, this method will be called allowing you to take the new value, convert it to an integer and pass it through an NSNumberFormatter, then update the UILabel to show this formatted value.

static NSNumberFormatter *formatter;

- (BOOL)textField:(UITextField *)aTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{   
    NSString *textFieldValue = [aTextField.text stringByAppendingString:string];

    if (range.length > 0)
        textFieldValue = [aTextField.text substringToIndex:range.location];

    if ([textFieldValue isEqualToString:@""])
        self.formattedLabel.text = textFieldValue;
    else
    {
        NSDecimalNumber *newValue = [[NSDecimalNumber alloc] initWithString:textFieldValue];
        if (!formatter) formatter = [[NSNumberFormatter alloc] init];
        formatter.numberStyle = NSNumberFormatterDecimalStyle;
        self.formattedLabel.text = [formatter stringFromNumber:newValue];
    }

    return YES;
}
0

精彩评论

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

关注公众号