ios 定时 button

来源:互联网 发布:淘宝客引流方法 编辑:程序博客网 时间:2024/06/07 00:25

1.设置 button



2.自定义 button
#import "Button_TimeButton.h"@interface Button_TimeButton()@property (nonatomic,strong) UILabel *label_TextLabel;@end@implementation Button_TimeButton- (instancetype)initWithCoder:(NSCoder *)aDecoder{    self = [super initWithCoder:aDecoder];    if (self) {                [self addView];        [self addTarget:self action:@selector(openCountdown) forControlEvents:UIControlEventTouchDown];    }    return self;}- (void) addView{        CGRect rect = self.frame;    self.label_TextLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)];    self.label_TextLabel.font = [UIFont fontWithName:@"Arial" size:16];    self.label_TextLabel.text = @"发送验证码";    self.label_TextLabel.textColor = [UIColor colorWithRed:72.0/255 green:127.0/255 blue:241.0/255 alpha:1.0f];    [self addSubview:self.label_TextLabel];}// 开启倒计时效果-(void)openCountdown{        self.label_TextLabel.text = @"";    __block NSInteger time = 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(time <= 0){ //倒计时结束,关闭                        dispatch_source_cancel(_timer);            dispatch_async(dispatch_get_main_queue(), ^{                                //设置按钮的样式                [self setTitle:@"重新发送" forState:UIControlStateNormal];                [self setTitleColor:[UIColor colorWithRed:72/255 green:127/255 blue:241/255 alpha:1.0f] forState:UIControlStateNormal];                self.userInteractionEnabled = YES;            });                    }else{                        int seconds = time % 60;            dispatch_async(dispatch_get_main_queue(), ^{                                //设置按钮显示读秒效果                [self setTitle:[NSString stringWithFormat:@"%.2d秒", seconds] forState:UIControlStateNormal];                [self setTitleColor:[UIColor colorWithRed:72.0/255 green:127.0/255 blue:241.0/255 alpha:1.0f] forState:UIControlStateNormal];                self.userInteractionEnabled = NO;            });            time--;        }    });    dispatch_resume(_timer);        }@end


3.button 的type 必须修改,不然就会闪烁

4. 借鉴了http://www.jianshu.com/p/2104865e7dba
















0 0
原创粉丝点击