在APP開發(fā)中,點擊獲取驗證碼的倒計時按鈕 是在注冊、修改密碼喜爷、綁定手機號等場景中使用耍属!在項目中,多次使用這個按鈕损趋,現(xiàn)自定義一個簡單的獲取短信驗證碼倒計時功能患久。
獲取短信驗證碼.png
如果需要,可以直接拿走這個自定義的按鈕ZLVerifyCodeButton浑槽,只需要調(diào)用方法即可蒋失,也可以在自定義里按照自己需求去更改按鈕的UI。
由于有些時間需求不同桐玻,特意露出方法篙挽,倒計時時間次數(shù):
- (void)timeFailBeginFrom:(NSInteger)timeCount;
自定義獲取驗證碼按鈕:
- (void)setup {
[self setTitle:@" 獲取驗證碼 " forState:UIControlStateNormal];
self.titleLabel.font = [UIFont systemFontOfSize:10];
self.backgroundColor = [UIColor clearColor];
self.layer.cornerRadius = 3.0;
self.clipsToBounds = YES;
[self setTitleColor:ZLColor(128, 177, 34) forState:UIControlStateNormal];
self.layer.borderColor = ZLColor(128, 177, 34).CGColor;
self.layer.borderWidth = 1.0;
}
倒計時方法:
- (void)timeFailBeginFrom:(NSInteger)timeCount {
self.count = timeCount;
self.enabled = NO;
// 加1個計時器
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
}
計時器方法:
- (void)timerFired {
if (self.count != 1) {
self.count -= 1;
self.enabled = NO;
[self setTitle:[NSString stringWithFormat:@"剩余%ld秒", self.count] forState:UIControlStateNormal];
// [self setTitle:[NSString stringWithFormat:@"剩余%ld秒", self.count] forState:UIControlStateDisabled];
} else {
self.enabled = YES;
[self setTitle:@"獲取驗證碼" forState:UIControlStateNormal];
// self.count = 60;
[self.timer invalidate];
}
}
在你所需要的控制器里調(diào)用這個短信驗證碼按鈕即可:
1)初始化創(chuàng)建設置相關按鈕屬性
// 獲取驗證碼按鈕
@property (nonatomic, weak) ZLVerifyCodeButton *codeBtn;
// 獲取驗證碼按鈕
ZLVerifyCodeButton *codeBtn = [ZLVerifyCodeButton buttonWithType:UIButtonTypeCustom];
// 設置frame 這里我是按照自己需求來
codeBtn.frame = CGRectMake(codeField.width - codeBtnW - marginX, 10, codeBtnW, 30);
[codeBtn addTarget:self action:@selector(codeBtnVerification) forControlEvents:UIControlEventTouchUpInside];
[self.codeField addSubview:codeBtn];
self.codeBtn = codeBtn;
2)調(diào)取后臺接口,獲取短信驗證碼處理相關其他邏輯
// 獲取驗證碼點擊事件
- (void)codeBtnVerification {
// 調(diào)用短信驗證碼接口
// 用戶輸入的驗證碼數(shù)字傳給server镊靴,判斷請求結(jié)果作不同的邏輯處理铣卡,根據(jù)自己家的產(chǎn)品大大需求來即可....
// if (請求成功且匹配成功驗證碼數(shù)字){
[self.codeBtn timeFailBeginFrom:60]; // 倒計時60s
} else {
[self.codeBtn timeFailBeginFrom:1]; // 處理請求成功但是匹配不成功的情況,并不需要執(zhí)行倒計時功能
}
}
這樣就OK了偏竟,可以測試看下呦~
效果圖
由于 Demo整體測試運行效果 , 整個修改密碼界面都已展現(xiàn), 并附送正則表達式及修改密碼邏輯!