您的位置:首页 > 移动开发 > IOS开发

iOS项目中获取验证码倒计时及闪烁问题解决方案

2015-12-25 19:56 627 查看
大家在做验证码的时候一般都会用到倒计时,基本上大家实现的方式都差不多,先贴出一些代码来..

-(void)startTime{

__block int timeout= 59; //倒计时时间

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行

dispatch_source_set_event_handler(_timer, ^{

if(timeout<=0){ //倒计时结束,关闭

dispatch_source_cancel(_timer);

dispatch_async(dispatch_get_main_queue(), ^{

//设置界面的按钮显示 根据自己需求设置

[self.getIdentifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];

self.getIdentifyBtn.userInteractionEnabled = YES;

});

}else{

// int minutes = timeout / 60;

int seconds = timeout % 60;

NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];

dispatch_async(dispatch_get_main_queue(), ^{

//设置界面的按钮显示 根据自己需求设置

[UIView beginAnimations:nil context:nil];

[UIView setAnimationDuration:1];

[self.getIdentifyBtn setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];

[UIView commitAnimations];

self.getIdentifyBtn.userInteractionEnabled = NO;

});

timeout--;

}

});

dispatch_resume(_timer);

}

上面代码的btn是我自己的,看客们根据自己项目来修改,那么还有一个问题,有时候用xib创建了按钮,做了倒计时,你会发现按钮倒计时的时候会发生闪烁的问题,那么解决方法是:

修改你的button的属性,如果是xib很简单,直接到button的属性中把按钮由默认的system改成custom即可,如果是代码创建,在创建的时候用

self.smsButton = [UIButton createButtonWithStyle:UIButtonTypeRoundedRect

withFrame:CGRectMake(80, 0, 100, 30)

                withTitle:NSLocalizedString(@"重发验证码", nil)

                withTitleColor:color

                withBackgroudColor:nil

                withNormalImage:nil

                withHighlightedImage:nil

                withNormalBackgroudImage:nil

}];

不可直接设置buttontype因为buttontype属性是readonly的!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: