简单的“获取验证码”的按钮功能实现

475 阅读1分钟

获取码证码,通常这种界面直接用xib来布局这个注册页面,以往用的是纯代码,然后发现了一个小bug,以前用纯代码写的获取验证码这个功能正常的,但是现在用xib拖拽的按钮,虽然可以实现,但是文字会闪烁,这到底是为什么纯代码没有问题,xib就出现这个问题,原因就是xib或者sb拖拽的button系统默认是system,system点击会出现一种高亮的状态,所以改变type就可以解决这个闪烁的问题了(通常使用custom类型)


#import "ViewController.h"
@interface ViewController ()
 
/* 时间 */
@property (nonatomic, assign) int timeCount;
/* 定时器 */
@property (nonatomic, strong) NSTimer *timer;
/* 按钮 */
@property (nonatomic, weak) UIButton *messageButton;
 
@end
 
@implementation ViewController
 
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    //创建按钮
    UIButton *btn = [[UIButton alloc] init];
    [btn addTarget:self action:@selector(sendMessageClick) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:@"获取码证码" forState:UIControlStateNormal];
    btn.frame = CGRectMake(100, 100, 200, 40);
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor redColor];
    [self.view addSubview:btn];
    self.messageButton = btn;
}
 
//监听
- (void)sendMessageClick
{
    self.messageButton.backgroundColor = [UIColor grayColor];
    self.messageButton.userInteractionEnabled = NO;
    //开始倒计时
    [self beginCalculationTime];
}
 
//开始倒计时
- (void)beginCalculationTime
{
    self.timeCount = 10;
    [self.messageButton setTitle:@"重新获取(60)" forState:UIControlStateNormal];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(refreshTime) userInfo:nil repeats:YES];
    [self.timer fire];
}
 
//timer
- (void)refreshTime
{
    self.label.text = [NSString stringWithFormat:@"重新获取(%ld)",(long)self.timeCount];
    self.timeCount -= 1;
    [self.messageButton setTitle:[NSString stringWithFormat:@"重新获取(%ld)",(long)self.timeCount] forState:UIControlStateNormal];
    if (self.timeCount == 0) {
        [self.messageButton setTitle:@"重新获取" forState:UIControlStateNormal];
        [self.timer invalidate];
        self.messageButton.userInteractionEnabled = YES;
        self.messageButton.backgroundColor = [UIColor redColor];
    }
}
 
@end