首先,有各種版本
方法一:
我運用的一種極其簡單的版本: 將UIButton的Type 設成 Custom 就不會有閃爍的問題重現
@property (strong, nonatomic) IBOutlet UIButton *getCodeBtn;
@property (nonatomic, strong) NSTimer *timerCode; //驗證碼定時器
__block int leftTime;
- (void)dealloc {
if ([_timerCode isValid]) {
[_timerCode invalidate];
_timerCode = nil;
}
}
#pragma mark - 驗證碼
//重新發送驗證碼
- (IBAction)resendCodeBtnPressed:(UIButton *)sender {
//判斷哪一個網絡請求發送驗證碼
//...
sender.enabled = NO;
leftTime = 60;
[self startOneTimer];
//發送驗證碼請求
[self.viewModel requestWithSendCode:[kUSERDEFAULT objectForKey:_isResetPassword? kForgetMobile:kLoginMobile] block:^(BOOL flag) {
}];
}
/**
* 發送驗證碼之后等待若干時間
*/
- (void)startOneTimer {
_getCodeBtn.enabled = NO;
leftTime = 60;
_timerCode = [NSTimer scheduledTimerWithTimeInterval:1 block:^{
if (leftTime == 0) {
_getCodeBtn.enabled = YES;
[_getCodeBtn setTitle:@"重新發送" forState:UIControlStateNormal];
[_getCodeBtn setTitleColor:fcc639 forState:UIControlStateNormal];
//計時完成,銷毀定時器
[_timerCode invalidate];
_timerCode = nil;
leftTime = 60;
return ;
}
leftTime--;
[_getCodeBtn setTitle:[NSString stringWithFormat:@"%i秒后重發", leftTime] forState:UIControlStateNormal];
[_getCodeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
} repeats:YES];
}
方法二: 就是在UIButton上罩一個同樣大小的UILabel,然后每次刷新UILabel的文字,不刷新按鈕,效果不錯,不再閃爍了
鏈接 :http://blog.csdn.net/kyfxbl/article/details/17619221
方法三:https://www.cnblogs.com/manji/p/4813520.html
補充: 我的方法中運用了 防止timer沒有被銷毀掉的timerBlocks 請自行查找
// NSTimer+Blocks.h
//
// Created by Jiva DeVoe on 1/14/11.
// Copyright 2011 Random Ideas, LLC. All rights reserved.