user2789934
user2789934

Reputation: 265

How do I format UITextField text in real time, while it's being edited?

How can I change value of UITextField text while typing?

In other word:

when I type 1 it should show 1

when I type 10 it should show 10

when I type 100 it should show 100 but

when I type 1000 it should show 1,000

Can you give any idea?

Upvotes: 13

Views: 12567

Answers (6)

Viktoryia
Viktoryia

Reputation: 69

  1. Be sure that textField.keyboardType = .numberPad

  2. Implement the UITextFieldDelegate method:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
    guard let text = textField.text else {
        return true
    }
    
    let modifiedText = (text as NSString).replacingCharacters(in: range, with: string)
    
    let formatter = NumberFormatter()
    formatter.usesGroupingSeparator = true
    formatter.numberStyle = .decimal
    formatter.groupingSeparator = ","
    
    let modifiedTextWithoutGroupingSeparator = modifiedText.replacingOccurrences(of: formatter.groupingSeparator, with: "")
    
    if let formattedNumber = formatter.number(from: modifiedTextWithoutGroupingSeparator) {
        textField.text = formatter.string(from: formattedNumber)
    }
    
    return false
    }
    

Upvotes: -1

imb
imb

Reputation: 23

add action:

self.amountTextField.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: .editingChanged)

in action:

@objc func textFieldDidChange(textField: UITextField) {
    if textField == amountTextField {
        
        var textFormatted = textField.text?.replacingOccurrences(of: ".", with: "")
        textFormatted = textFormatted?.replacingOccurrences(of: ".", with: "")

        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        if let text = textFormatted, let intVal = Int(text) {
            textField.text = formatter.string(from: NSNumber(value: intVal))
        }
    }
}

Upvotes: 1

Juan Boero
Juan Boero

Reputation: 6417

Swift:

Be sure to select the text field input as number pad, then:

In your viewDidLoad:

yourTextField(self, action: #selector(self.textFieldDidChange(textField:)), for: .editingChanged)

Then, in that same view controller:

func textFieldDidChange(textField: UITextField) {
        if textField == yourTextField {

            // Some locales use different punctuations.
            var textFormatted = textField.text?.replacingOccurrences(of: ",", with: "")
            textFormatted = textFormatted?.replacingOccurrences(of: ".", with: "")

            let numberFormatter = NumberFormatter()
            numberFormatter.numberStyle = .decimal
            if let text = textFormatted, let textAsInt = Int(text) {
                textField.text = numberFormatter.string(from: NSNumber(value: textAsInt))
            }
        }
    }

Upvotes: 1

KK.
KK.

Reputation: 206

Add a "textFieldDidChange" notification method to the text field control.

[textField addTarget:self
              action:@selector(textFieldDidChange:)
    forControlEvents:UIControlEventEditingChanged];


-(void)textFieldDidChange:(UITextField *)theTextField
{
    NSLog(@"text changed: %@", theTextField.text);

    NSString *textFieldText = [theTextField.text stringByReplacingOccurrencesOfString:@"," withString:@""];

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSString *formattedOutput = [formatter stringFromNumber:[NSNumber numberWithInt:[textFieldText integerValue]]];
    textField.text=formattedOutput;            
}

Upvotes: 18

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39988

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init] ;
    if([string length]==0)
    {
        [formatter setGroupingSeparator:@","];
        [formatter setGroupingSize:4];
        [formatter setUsesGroupingSeparator:YES];
        [formatter setSecondaryGroupingSize:3];
        NSString *num = textField.text ;
        num = [num stringByReplacingOccurrencesOfString:@"," withString:@""];
        NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[num doubleValue]]];
        textField.text = str;
        return YES;
    }
    else {
        [formatter setGroupingSeparator:@","];
        [formatter setGroupingSize:2];
        [formatter setUsesGroupingSeparator:YES];
        [formatter setSecondaryGroupingSize:3];
        NSString *num = textField.text ;
        if(![num isEqualToString:@""])
        {
            num = [num stringByReplacingOccurrencesOfString:@"," withString:@""];
            NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[num doubleValue]]];
            textField.text = str;
            NSLog(@"add:%@",str);
        }
        return YES;
    }
}

P.S. This code is in ARC, take care of memory management in non arc environment.

Upvotes: 4

kalyani puvvada
kalyani puvvada

Reputation: 496

Try this one.. You can write following line in ViewDidLoad method and give delegate to the textfield.

[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

and write the following method.

-(void)textFieldDidChange:(UITextField*)textfield{
  NSLog(@"here %@",textfield.text);
  if ([textfield.text isEqualToString:@"1000"]) {
    textfield.text=@"1,000";
  }
}

Upvotes: -3

Related Questions