textFiled输入的数字添加分字符“,”

输入的数字表示金额时,习惯三位数字进行一次区分,一般情况下常用“,”
用NSString的扩展类实现这个效果

#import 
@interface NSString (YT_character)
//字符串中的数字每3位增加一个 “逗号”
+ (NSMutableAttributedString *)stringBySeparatorForString:(NSString *)string;
@end
#import "NSString+YT_character.h"
@implementation NSString (YT_character)
//字符串的数字中间添加 “,”
+ (NSMutableAttributedString *)stringBySeparatorForString:(NSString *)num {
    if (num == nil) {
        num = @"0";
    }
    NSString *newString = [num stringByReplacingOccurrencesOfString:@"," withString:@""];
    NSNumberFormatter *fomatter = [[NSNumberFormatter alloc] init];
    [fomatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSString *formatterStr = [fomatter stringFromNumber:[NSNumber numberWithInteger:[newString integerValue]]];
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",formatterStr] attributes:nil];
    return attString;
}
@end

控制器中使用的方法,使用监听事件的方式

    [_zijinTextField addTarget:self action:@selector(textFiledTextChange:) forControlEvents:UIControlEventEditingChanged];
//text输入框数字区分
- (void)textFiledTextChange:(UITextField *)textfile {
    textfile.attributedText = [NSString stringBySeparatorForString:textfile.text];
    if ([textfile.text isEqualToString:@"0"]) {
        textfile.text = @"";
    }
}

你可能感兴趣的:(textFiled输入的数字添加分字符“,”)