之前项目中写手机充值用到输入手机号格式的,现在把他写出来;
在viewDidload里令i=0;
#pragma mark - textField输入内容
-(void)textFieldDidChange:(UITextField *)phoneNum
{
phoneNum.font = [UIFont systemFontOfSize:28];
// NSLog(@"%@",phoneNum.text);
if (phoneNum.text.length > i) {
if (phoneNum.text.length == 4 || phoneNum.text.length == 9 ) {//输入
NSMutableString * str = [[NSMutableString alloc ] initWithString:phoneNum.text];
[str insertString:@" " atIndex:(phoneNum.text.length-1)];
phoneNum.text = str;
}if (phoneNum.text.length >= 13 ) {//输入完成
phoneNum.text = [phoneNum.text substringToIndex:13];
[phoneNum resignFirstResponder];
//正则判断手机号
NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|7[01678]|8[0-9])\\d{8}$";
NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[08]|8[2-478])\\d{8}$";
NSString *CU = @"^1(3[0-2]|4[5]|5[256]|7[016]|8[56])\\d{8}$";
NSString *CT = @"^1(3[34]|53|7[07]|8[019])\\d{8}$";
NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
self.textFieldStr = [phoneNum.text stringByReplacingOccurrencesOfString:@" "withString:@""];
if (([regextestmobile evaluateWithObject:self.textFieldStr]
|| [regextestcm evaluateWithObject:self.textFieldStr]
|| [regextestct evaluateWithObject:self.textFieldStr]
|| [regextestcu evaluateWithObject:self.textFieldStr])) {
// NSLog(@"手机号正确");
//做一些事情
}else{
// NSLog(@"手机号错误");
self.guishudiL.text = @"您输入的号码错误";
}
}
i = phoneNum.text.length;
}else if (phoneNum.text.length < i){//删除
if (phoneNum.text.length == 4 || phoneNum.text.length == 9) {
phoneNum.text = [NSString stringWithFormat:@"%@",phoneNum.text];
phoneNum.text = [phoneNum.text substringToIndex:(phoneNum.text.length-1)];
}else if (phoneNum.text.length == 0){
[phoneNum mas_updateConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(15);
make.left.equalTo(20);
make.height.equalTo(35);
}];
phoneNum.font = [UIFont systemFontOfSize:15];
self.guishudiL.text = @"";
}else if (phoneNum.text.length == 12){
[self.cheaperArray removeAllObjects];
[self.rechargeCollectView reloadData];
}
i = phoneNum.text.length;
}else if (phoneNum.text.length == 0){
[phoneNum mas_updateConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(15);
make.left.equalTo(20);
}];
phoneNum.font = [UIFont systemFontOfSize:15];
self.guishudiL.text = @"";
[self.cheaperArray removeAllObjects];
[self.rechargeCollectView reloadData];
}
}
到此可以实现单个删除一个数字,全部删除都可以,还可以实现复制过来的电话号码格式化;