Format currency with UITextField

前端 未结 1 617
小蘑菇
小蘑菇 2021-01-26 11:46

I have a UITextField that the user will enter an amount of money. I want to set it so it will show the users current currency. I could do the following:

<         


        
相关标签:
1条回答
  • 2021-01-26 12:26

    If you are using ReactiveCocoa you can try doing this.

    [textField.rac_textSignal subscribeNext:^(NSString *text) {
        if (text.length < 4) text = @"0.00";
    
        //set currency style
        NSNumberFormatter *currencyFormatter = [NSNumberFormatter new];
        currencyFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
    
        //leave only decimals (we want to get rid of any unwanted characters)
    
        NSString *decimals = [[text componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];
    
        //insert decimal separator
        NSMutableString *mutableString = [NSMutableString stringWithString:decimals];
        [mutableString insertString:currencyFormatter.decimalSeparator atIndex:mutableString.length - currencyFormatter.minimumFractionDigits];
    
        //I add currency symbol so that formatter recognizes decimal separator while formatting to NSNumber
        NSString *result = [currencyFormatter.currencySymbol stringByAppendingString:mutableString];
    
        NSNumber *formattedNumber = [currencyFormatter numberFromString:result];
        NSString *formattedText = [currencyFormatter stringFromNumber:formattedNumber];
    
        //saving cursors position 
        UITextRange *position = textField.selectedTextRange;
    
        textField.text = formattedText;
    
        //reassigning cursor position (Its not working properly due to commas etc.)
        textField.selectedTextRange = position;
    }];
    

    It's not perfect, but maybe this can help you a bit in finding correct solution.

    0 讨论(0)
提交回复
热议问题