最近项目接近尾声, 将项目中遇到的问题, 分享一下.
具体要求电话号码3位, 7位, 11位中间加入分隔符"-"
//控制textfield输入长度
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField == self.newtextfield || textField == self.agenntextfield) {
//这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
if (range.length == 1 && string.length == 0) {
return YES;
}else if (textField.text.length == 11) {
textField.text = [textField.text substringToIndex:11];
[textField resignFirstResponder];
return NO;
}
}
return YES;
}
//当textfield成为第一响应者的时候
- (void)textFieldDidBeginEditing:(UITextField *)textField{
if ((textField.tag == 1)) {
NSMutableString * str = [[NSMutableString alloc] initWithString:self.newtextfield.text];
for (int a = 0; a < str.length; a++) {
unichar c = [str characterAtIndex:a];
NSRange range = NSMakeRange(a, 1);
if (c == '-'){ //此处可以是任何字符
[str deleteCharactersInRange:range];
--a;
}
}
self.newtextfield.text = str;
} else if (textField.tag == 2){
NSMutableString * str = [[NSMutableString alloc ] initWithString:self.agenntextfield.text];
for (int a = 0; a < str.length; a++) {
unichar c = [str characterAtIndex:a];
NSRange range = NSMakeRange(a, 1);
if (c == '-'){ //此处可以是任何字符
[str deleteCharactersInRange:range];
--a;
}
}
self.agenntextfield.text = str;
}
}
//当textfield失去第一响应者的时候触发
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
if (textField.tag == 1) {
NSMutableString * str = [[NSMutableString alloc] initWithString:self.newtextfield.text];
[textField resignFirstResponder];
for (int a = 0; a < str.length; a++) {//加入@"-"
if (a == 3) {
[str insertString:@"-" atIndex:a];
} else if (a == 8){
[str insertString:@"-" atIndex:a];
}
}
self.newtextfield.text = str;
} else if (textField.tag == 2){
NSMutableString * str = [[NSMutableString alloc] initWithString:self.agenntextfield.text];
[textField resignFirstResponder];
for (int a = 0; a < str.length; a++) {//加入@"-"
if (a == 3) {
[str insertString:@"-" atIndex:a];
} else if (a == 8){
[str insertString:@"-" atIndex:a];
}
}
self.agenntextfield.text = str;
}
return YES;
}