iOS 短信验证码


<pre name="code" class="objc">NSString *const KTitleStr = @"获取验证码";
NSInteger const KTimeNum = 20;

 
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self setTitle:KTitleStr forState:UIControlStateNormal];
        [self setBackgroundColor:[UIColor blueColor]];
        self.titleLabel.font=[UIFont systemFontOfSize:12];
        [self setTitle:@"" forState:UIControlStateHighlighted];
        [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.userInteractionEnabled = YES;
        _timeNumber = KTimeNum;
        [self addTarget:self action:@selector(btnTitleChange:) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}
- (void)btnTitleChange:(UIButton *)btn
{
    // 创建倒计时
    _timer = [NSTimer scheduledTimerWithTimeInterval:_timeInterval target:self selector:@selector(timeChanges) userInfo:NULL repeats:YES];
    [_timer fire];
}
- (void)timeChanges
{
    if (_timeNumber == 0) {
        [self setTitle:KTitleStr forState:UIControlStateNormal];
        [self setBackgroundColor:[UIColor blueColor]];
        self.titleLabel.font=[UIFont systemFontOfSize:12];
        [self setTitle:@"" forState:UIControlStateHighlighted];
        [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.userInteractionEnabled = YES;
        _timeNumber = KTimeNum;
        [_timer invalidate];//停止timer
    } else {
        [self setBackgroundColor:[UIColor colorWithPatternImage:_downBgImg]];
        [self setTitle:[NSString stringWithFormat:@"%d",_timeNumber] forState:UIControlStateNormal];
        [self setTitle:[NSString stringWithFormat:@"%d",_timeNumber] forState:UIControlStateHighlighted];
        self.userInteractionEnabled = NO;
        _timeNumber -= 1;
    }
}

简单封装一个短信验证码按钮

1. 创建按钮,添加点击事件

2. 创建NSTimer 倒计时,定义NSTimerInterVal触发间隔

设置属性外边调用



@interface AuthButton : UIButton
{
    @private
    NSTimer *_timer;
}
/**
 *  触发间隔
 */
@property (nonatomic, assign) NSTimeInterval timeInterval;
/**
 *  时钟
 */
@property (nonatomic, strong, readonly) NSTimer *timer;

/**
 *  倒计时按钮背景
 */
@property (nonatomic, strong) UIImage *downBgImg;
@end



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值