最新项目中要实现手机号码格式为(XXX-XXXX-XXXX)的效果,在查阅了一些资料后我把自己的代码贴出来与大家一起分享下。
@implementation CustomStyleOneView {
NSInteger i;//定义全局变量
}
self.nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.nameLab.frame) + 12 * HMWidth, 0, self.frame.size.width - CGRectGetMaxX(self.nameLab.frame) - 75 * HMWidth, self.frame.size.height / 2 - HMHeight)];
self.nameTextField.keyboardType = UIKeyboardTypeASCIICapableNumberPad;
self.nameTextField.placeholder = @"请输入正确的手机号";
self.nameTextField.font = [UIFont systemFontOfSize:15];
self.nameTextField.textColor = [UIColor hx_colorWithHexRGBAString:@"#212121"];
[self.nameTextField addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
self.nameTextField.delegate = self;
[self addSubview:self.nameTextField];
#pragma mark - TextField 电话号自动加 "-"
/**
//备注:当到第四位或第九位时,如果此时是正在输入,则自动增加空格,如果正在删除,则自动删除空格!!!
//当到第13位时,截取前面的13位字符串,收起键盘
//若想要获取输入的手机,需要先删除空格; NSString *textFieldStr =[self.textField.textstringByReplacingOccurrencesOfString:@" "withString:@""];
*/
- (void)textFieldDidChanged:(UITextField *)textField{
if (textField == self.nameTextField) {
if (textField.text.length > i) {
if (textField.text.length == 4 || textField.text.length == 9 ) {//输入
NSMutableString * str = [[NSMutableString alloc ] initWithString:textField.text];
[str insertString:@"-" atIndex:(textField.text.length-1)];
textField.text = str;
}if (textField.text.length >= 13 ) {//输入完成
textField.text = [textField.text substringToIndex:13];
[textField resignFirstResponder];
}
i = textField.text.length;
}else if (textField.text.length < i){//删除
if (textField.text.length == 4 || textField.text.length == 9) {
textField.text = [NSString stringWithFormat:@"%@",textField.text];
textField.text = [textField.text substringToIndex:(textField.text.length-1)];
}
i = textField.text.length;
}
}else if (textField == self.verifcationTextField) {
/**验证码大于4位跳出焦点*/
if (textField.text.length >= 4) {
[textField resignFirstResponder];
NSString *str = self.nameTextField.text;
str = [str stringByReplacingOccurrencesOfString:@"-" withString:@""];
self.accountBlock(str, self.verifcationTextField.text);
}
}
}
效果图如下: