iOS登錄時驗證手機號與倒計時發(fā)送驗證碼問題詳解
前言
我們做登錄的時候經(jīng)常會使用到,驗證手機號是否正確、向手機發(fā)送驗證碼倒計時60s的問題,我們改如何解決呢?讓我們一起來探討一下吧。
如下圖:

首先,我們先說說判斷手機號碼是否正確的問題吧,我的想法是給字符串添加一個分類,然后寫上這樣的代碼:
+ (BOOL)valiMobile:(NSString *)mobile{
if (mobile.length != 11){
//判斷手機號碼是否為11位
return NO;
}else{
//使用正則表達式的方法來判斷手機號
/**
* 移動號段正則表達式
*/
NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
/**
* 聯(lián)通號段正則表達式
*/
NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
/**
* 電信號段正則表達式
*/
NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
//初始化NSPredicate對象
NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
//與具體對象進行篩選判斷, 返回為BOOL值
BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
if (isMatch1 || isMatch2 || isMatch3) {
return YES;
}else{
return NO;
}
}
}
如果大家對于NSPredicate的用法有些疑問的話可以看看這篇文章:http://www.dbjr.com.cn/article/155004.htm
下面再來說一說驗證碼倒計時的問題,
1、我給button創(chuàng)建了一個分類
2、設定button上的文字,并記錄倒計時的總時長,然后開一個定時器,并且關閉button的點擊事件
3、定時器中將總時間縮減,并且設置button的文字,然后做一個判斷,判斷時間是否歸為0,如果為0 就釋放定時器,然后設置button上的文字,然后打開用戶交互。
代碼如下:
.h文件中
#import@interface UIButton (BtnTime) /** 按鈕倒計時的問題 @param countDownTime 倒計時的時間(分鐘) */ - (void)buttonWithTime:(CGFloat)countDownTime; @end
.m文件中
#import "UIButton+BtnTime.h"
/** 倒計時的顯示時間 */
static NSInteger secondsCountDown;
/** 記錄總共的時間 */
static NSInteger allTime;
@implementation UIButton (BtnTime)
- (void)buttonWithTime:(CGFloat)countDownTime {
self.userInteractionEnabled = NO;
secondsCountDown = 60 * countDownTime;
allTime = 60 * countDownTime;
[self setTitle:[NSString stringWithFormat:@"%lds后重新獲取",secondsCountDown] forState:UIControlStateNormal];
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod:) userInfo:nil repeats:YES];
}
-(void)timeFireMethod:(NSTimer *)countDownTimer{
//倒計時-1
secondsCountDown--;
//修改倒計時標簽現(xiàn)實內容
[self setTitle:[NSString stringWithFormat:@"%lds后重新獲取",secondsCountDown] forState:UIControlStateNormal];
//當?shù)褂嫊r到0時,做需要的操作,比如驗證碼過期不能提交
if(secondsCountDown == 0){
[countDownTimer invalidate];
[self setTitle:@"重新獲取" forState:UIControlStateNormal];
secondsCountDown = allTime;
self.userInteractionEnabled = YES;
}
}
@end
代碼已經(jīng)上傳到github上去了,地址:https://github.com/zhangyqyx/Countdown (本地下載)
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
Flutter?ScrollController滾動監(jiān)聽及控制示例詳解
這篇文章主要為大家介紹了Flutter?ScrollController滾動監(jiān)聽及控制示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11
IOS網(wǎng)絡請求之NSURLSession使用詳解
這篇文章主要介紹了IOS網(wǎng)絡請求之NSURLSession使用詳解,今天使用NSURLConnection分別實現(xiàn)了get、post、表單提交、文件上傳、文件下載,有興趣的可以了解一下。2017-02-02

