最近写的项目有这个需求,看了别人写的,打算自己写一份备用
这是原文[http://blog.csdn.net/h3c4lenovo/article/details/8515304]
- 第一步需要有一个textField,遵守协议,实现代理
self.mytextfield.delegate = self;
-然后需要实现的代理方法就是这个
- (BOOL)textField:(UITextField )textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString )string{
//判断是否是当前输入框
if (self.mytextfield == textField) {
NSString text = self.mytextfield.text;
//限制字符 至于那个\b用在search中 写不写都行
NSCharacterSet characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
//去掉空格
string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
//检查除数字之外的字符 invertedSet:意思是取反,除了数字和退格的内容
if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
return NO;
}
//拼接text 要输入的部分+原有的
text = [text stringByReplacingCharactersInRange:range withString:string];
//去空格
text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString newString = @"";
//四位添加空格
while (text.length > 0) {
NSString subString = [text substringToIndex:MIN(text.length, 4)];
newString = [newString stringByAppendingString:subString];
if (subString.length == 4) {
newString = [newString stringByAppendingString:@" "];
}
text = [text substringFromIndex:MIN(text.length, 4)];
}
//去掉除数字部分
newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
// 限制长度
if (newString.length >= 24) {
return NO;
}
//赋值
[self.mytextfield setText:newString];
return NO;
}
return YES;
}
基本就是这样,注释写的很详细了