iOS 简单的实现手机号正误的判断(Warning: Attempt to present... whose view is not in the window hierarchy!

- (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;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值