Re-Apply currency formatting to a UITextField on a change event

前端 未结 6 2123
日久生厌
日久生厌 2020-11-28 12:33

I\'m working with a UITextField that holds a localized currency value. I\'ve seen lots of posts on how to work with this, but my question is: how do I re-apply currency for

6条回答
  •  渐次进展
    2020-11-28 13:00

    Here's my version of this.

    Setup a formatter some place:

        // Custom initialization
        formatter = [NSNumberFormatter new];
        [formatter setNumberStyle: NSNumberFormatterCurrencyStyle];
        [formatter setLenient:YES];
        [formatter setGeneratesDecimalNumbers:YES];
    

    Then use it to parse and format the UITextField:

    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        NSString *replaced = [textField.text stringByReplacingCharactersInRange:range withString:string];
        NSDecimalNumber *amount = (NSDecimalNumber*) [formatter numberFromString:replaced];
        if (amount == nil) {
            // Something screwed up the parsing. Probably an alpha character.
            return NO;
        }
        // If the field is empty (the inital case) the number should be shifted to
        // start in the right most decimal place.
        short powerOf10 = 0;
        if ([textField.text isEqualToString:@""]) {
            powerOf10 = -formatter.maximumFractionDigits;
        }
        // If the edit point is to the right of the decimal point we need to do
        // some shifting.
        else if (range.location + formatter.maximumFractionDigits >= textField.text.length) {
            // If there's a range of text selected, it'll delete part of the number
            // so shift it back to the right.
            if (range.length) {
                powerOf10 = -range.length;
            }
            // Otherwise they're adding this many characters so shift left.
            else {
                powerOf10 = [string length];
            }
        }
        amount = [amount decimalNumberByMultiplyingByPowerOf10:powerOf10];
    
        // Replace the value and then cancel this change.
        textField.text = [formatter stringFromNumber:amount];
        return NO;
    }
    

提交回复
热议问题