- (void)viewDidLoad {
[super viewDidLoad];
/*这里粗略的写了一个按钮,
否则在viewDidLoad中直接运行checkTel方法会报错:
Warning: Attempt to present <UIAlertController: 0x7fea35236db0> on <ViewController: 0x7fea33d2f340> whose view is not in the window hierarchy!
原因是在presnet的时候viewDidLoad还没有执行完成,只有viewDidLoad执行完成之后,正常使用。
在控制器加载的时候,不能使用这个去调用,这样就必须向办法延时才行。
*/
UIButton * but = [[UIButton alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 100)/2, 100, 100, 100)];
[but setTitle:@"验证手机号" forState:UIControlStateNormal];
[but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.view addSubview:but];
[but addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
}
//按钮的点事件
- (void)click{
//这里填手机号码
[self checkTel:@"123123"];
}
- (BOOL)checkTel:(NSString *)str
{
if ([str length] == 0) {
UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"温馨提示"
message:@"您输入的手机号不能为空"
preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *cancel =[UIAlertAction actionWithTitle:@"返回"
style:UIAlertActionStyleCancel
handler:nil];
[alert addAction:cancel];
[self presentViewController:alert animated:YES completion:nil];
return NO;
}
NSString *regex = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
BOOL isMatch = [pred evaluateWithObject:str];
if (!isMatch) {
UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"温馨提示"
message:@"请输入正确的手机号码"
preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *cancel =[UIAlertAction actionWithTitle:@"返回"
style:UIAlertActionStyleCancel
handler:nil];
[alert addAction:cancel];
[self presentViewController:alert animated:YES completion:nil];
return NO;
}
return YES;
}