监听UITextfield值变化
_phoneNumTextfield.delegate = self;
//textField变化时事件
[_phoneNumTextfield addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
定义成员变量
NSString *previousTextFieldContent;
UITextRange *previousSelection;
代理方法
- (void)textFieldEditingChanged:(UITextField *)textField {
//限制手机账号长度13位(有两个空格)
if (textField.text.length > 13) {
textField.text = [textField.text substringToIndex:13];
}
NSUInteger targetCursorPosition = [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
NSString *currentStr = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString *preStr = [previousTextFieldContent stringByReplacingOccurrencesOfString:@" " withString:@""];
//正在执行删除操作时为0,否则为1
char editFlag = 0;
if (currentStr.length <= preStr.length) {
editFlag = 0;
} editFlag = 1;
NSMutableString *tempStr = [NSMutableString new];
int spaceCount = 0;
if (currentStr.length < 3 && currentStr.length > -1) {
spaceCount = 0;
}else if (currentStr.length < 7 && currentStr.length > 2) {
spaceCount = 1;
}else if (currentStr.length < 12 && currentStr.length > 6) {
spaceCount = 2;
}
for (int i = 0; i < spaceCount; i++) {
if (i == 0) {
[tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(0, 3)], @" "];
}else if (i == 1) {
[tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(3, 4)], @" "];
}else if (i == 2) {
[tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(7, 4)], @" "];
}
}
if (currentStr.length == 11) {
[tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(7, 4)], @" "];
}
if (currentStr.length < 4) {
[tempStr appendString:[currentStr substringWithRange:NSMakeRange(currentStr.length - currentStr.length % 3, currentStr.length % 3)]];
}else if(currentStr.length > 3 && currentStr.length <12) {
NSString *str = [currentStr substringFromIndex:3];
[tempStr appendString:[str substringWithRange:NSMakeRange(str.length - str.length % 4, str.length % 4)]];
if (currentStr.length == 11) {
[tempStr deleteCharactersInRange:NSMakeRange(13, 1)];
}
}
textField.text = tempStr;
// 当前光标的偏移位置
NSUInteger curTargetCursorPosition = targetCursorPosition;
if (editFlag == 0) {
//删除
if (targetCursorPosition == 9 || targetCursorPosition == 4) {
curTargetCursorPosition = targetCursorPosition - 1;
}
}else {
//添加
if (currentStr.length == 8 || currentStr.length == 4) {
curTargetCursorPosition = targetCursorPosition + 1;
}
}
UITextPosition *targetPosition = [textField positionFromPosition:[textField beginningOfDocument] offset:curTargetCursorPosition];
[textField setSelectedTextRange:[textField textRangeFromPosition:targetPosition toPosition :targetPosition]];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
previousTextFieldContent = textField.text;
previousSelection = textField.selectedTextRange;
return YES;
}
试试吧
网友评论