iOS一个方法添加按钮计时器

作者: idage | 来源:发表于2016-05-19 19:49 被阅读3004次

引入一个类,然后只需要多一个方法,就可以让一个按钮有计时的功能,而且还可以通过一个block回调知道计时的状态,让代码简洁到爽。这对你有点诱惑吗?

使用的时候代码是这个样子的:
[button setDGTimerButtonWithDuration:50
                         runingColor:[UIColor grayColor]                                               runingTextColor:[UIColor whiteColor]
                       runingImgName:nil
                           formatStr:@"还剩%zd秒了"
                            buStatus:^(BUStatus status) {   
        if (status==BUStatusRuning) {
            //计时中
        }else if (status==BUStatusCancel){
            //结束了(手动结束了,没有超时)
        }else if (status==BUStatusFinish){
            //计时结束了 超时了
        }else{
           //没开始
        }
    }];

还有两个方法,来控制计时的开始和结束:

/**
 *  开始计时
 */
-(void)beginTimers;
/**
 *  结束计时
 */
-(void)stopTimers;

简单介绍

DGTimerButton类继承于UIButton。使用的时候和正常的UIButton是一样的,添加计时器功能就使用上面的那个方法,而且类会自动保存你按钮开始计时前的状态,计时结束的时候会返回原来的状态。(只会保存按钮的背景颜色、背景图片、文字和文字颜色。我感觉保存这些就够用了!)
代码注视写的很全,直接上.m文件了:

#import "DGTimerButton.h"
#import <objc/runtime.h>

@interface DGTimerButton()
/**
 *  控件的状态
 */
@property(nonatomic,assign)BUStatus statusType;
/**
 *  计时的时间
 */
@property(nonatomic,assign)NSInteger timeCount;
/**
 *  计时原始时间
 */
@property(nonatomic,assign)NSInteger oldTimeCount;
/**
 *  计时器
 */
@property(weak, nonatomic) NSTimer *timer;
/**
 *  按钮的初始背景色
 */
@property(nonatomic,strong)UIColor *normalBgColor;
/**
 *  按钮的初始背景图片
 */
@property(nonatomic,strong)UIImage *normalBgImg;
/**
 *  按钮默认情况下的文字颜色
 */
@property(nonatomic,strong)UIColor *normalTextColor;
@property(nonatomic,copy)NSString  *normalText;
@end
//用于关联block
static void *statusBlockKey = @"statusBlockKey";

@implementation DGTimerButton

//重写buttonWithType 方法 UIButtonTypeCustom按钮计时改变的时候不会闪动
+ (instancetype)buttonWithType:(UIButtonType)buttonType{
    
    return [super buttonWithType:UIButtonTypeCustom];
}
/**
 *  设置计时按钮的时长和状态的回调
 *
 *  @param durtaion   时间 单位秒
 *  @param bustatus   状态的回调
 */
-(void)setDGTimerButtonWithDuration:(NSInteger)durtaion buStatus:(void(^)(BUStatus status))bustatus{
    _timeCount      = durtaion;
    _oldTimeCount   = durtaion;
    _statusType     = BUStatusNone;
    
    objc_setAssociatedObject(self, statusBlockKey, bustatus, OBJC_ASSOCIATION_COPY);
    
    bustatus(BUStatusNone);
}
-(void)setDGTimerButtonWithDuration:(NSInteger)durtaion runingColor:(UIColor*)runingColor runingTextColor:(UIColor *)runingTextColor runingImgName:(NSString*)runingImgName buStatus:(void(^)(BUStatus status))bustatus{
    
    _runingImgName      =runingImgName;
    _runingColor        =runingColor;
    _runingTextColor    =runingTextColor;
    
    [self setDGTimerButtonWithDuration:durtaion buStatus:^(BUStatus status) {
        bustatus(status);
    }];
}
/**
 *  开始计时
 */
-(void)beginTimers{
    
  if (!self.timer) {
    NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(next) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;
  }
    //更新时间
    _timeCount = _oldTimeCount;
    //记录按钮的原始状态
    _normalBgColor       = self.backgroundColor;
    _normalBgImg         = self.currentBackgroundImage;
    _normalTextColor     = self.currentTitleColor;
    _normalText          = self.currentTitle;
    //设置按钮计时时的样式
    if (_runingColor) {
        [self setBackgroundColor:_runingColor];
    }
    if (_runingImgName.length>0) {
        [self setBackgroundImage:[UIImage imageNamed:_runingImgName] forState:UIControlStateNormal];
    }
    if (_runingTextColor) {
        [self setTitleColor:_runingTextColor forState:UIControlStateNormal];
    }
    //让按钮不可以点击
    self.userInteractionEnabled = NO;
    self.titleLabel.adjustsFontSizeToFitWidth=YES;
    [self.titleLabel setTextAlignment:NSTextAlignmentCenter];
    [self next];
    
    void (^statusBlock)(NSInteger) = objc_getAssociatedObject(self, statusBlockKey);
    statusBlock(BUStatusRuning);

}
/**
 *  结束计时
 */
-(void)stopTimers{
    [self.timer invalidate];
     self.timer = nil;
    void (^statusBlock)(NSInteger) = objc_getAssociatedObject(self, statusBlockKey);

    if (_timeCount ==0) {//超时了
        statusBlock(BUStatusFinish);
    }else{
        //结束了但没有超时
        statusBlock(BUStatusCancel);
    }
    //还原按钮样式
     [self setBackgroundImage:_normalBgImg forState:UIControlStateNormal];
     [self setBackgroundColor:_normalBgColor];
     [self setTitleColor:_normalTextColor forState:UIControlStateNormal];
     [self setTitle:_normalText forState:UIControlStateNormal];
      self.userInteractionEnabled = YES;
}
- (void)next
{
    if (_timeCount<1) {
        //结束了 超时了
        [self stopTimers];
    }else{
         //改文字
        if (_formatStr.length>0) {
           [self setTitle:[NSString stringWithFormat:_formatStr,_timeCount] forState:UIControlStateNormal];
        }else{
            [self setTitle:[NSString stringWithFormat:@"%zdS",_timeCount] forState:UIControlStateNormal];
        }
        _timeCount--;
    }
}
@end

github项目连接

相关文章

网友评论

    本文标题:iOS一个方法添加按钮计时器

    本文链接:https://www.haomeiwen.com/subject/hrugrttx.html