CPF和CNPJ的格式文本字段 [英] Format textfield for CPF and CNPJ

查看:136
本文介绍了CPF和CNPJ的格式文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应如何处理iOS中的文本格式?我不是在谈论货币或小数样式.由于iOS没有 setFormat(),因此有点复杂.

How should I handle text formatting in iOS? I'm not talking about Currency or Decimal styles. Since iOS doesn't have setFormat(), it's kind of complicated.

我想要的格式的两个示例: 123.456.789-10 123.456.789/1000-00 .

Two examples of the format I want: 123.456.789-10 and 123.456.789/1000-00.

我的目标是在用户键入内容时格式化文本字段.就像任何普通的网站一样,例如,当您键入电话号码时.它不是来自模型或其他任何东西.用户只需要输入数字,必要时我就插入.","/" -" .

My aim is to format a text field as the user types. Like any normal site does when, for example, you type a phone number. It doesn't comes from a model or anything. The user just needs to type the numbers and when necessary I'll insert the ".","/" or "-".

推荐答案

您可以使用正则表达式进行格式化,例如:

You can use regular expressions to do formatting, like this:

NSRegularExpression *fmt = [NSRegularExpression
    regularExpressionWithPattern:@"(.{1,3})(.{1,3})(.{1,3})(.{1,2})"
                         options:0
                           error:NULL];
NSMutableString *str = [NSMutableString stringWithString:@"12345678910"];
[fmt replaceMatchesInString:str
                    options:0
                      range:NSMakeRange(0, str.length)
               withTemplate:@"$1.$2.$3-$4"];

这会将字符串转换为 123.456.789-10

为了在用户键入时动态应用此格式,请预先创建 NSRegularExpression * fmt ,将其存储在 UITextFieldDelegate 中,并在 textField中使用它:shouldChangeCharactersInRange:replacementString:方法.

In order to apply this formatting dynamically as users type, create NSRegularExpression *fmt upfront, store it in your UITextFieldDelegate, and use it in your textField:shouldChangeCharactersInRange:replacementString: method.

这篇关于CPF和CNPJ的格式文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆