自定义计时器UIButton

2023-05-03,,

  1. 创建PWTimerButton 继承与UIButton

  2. 添加成员方法和属性

  3. 头文件如下:

@interface PWTimerButton : UIButton

{

    NSInteger _timerInterval;

    NSTimer *_timer;

    NSString *_formatString;

}

- (void)setFormatString:(NSString *)formatString;

- (void)startTimer:(NSInteger)interval;

- (void)stopTimer;

4.源文件如下:

- (void)startTimer:(NSInteger)interval

{

    if (_timer) {

        [_timer invalidate];

        _timer = nil;

    }

    if (interval > 0) {

        _timerInterval = interval;

        self.enabled = NO;

        [self updateButtonState];

        

        _timer = [NSTimer scheduledTimerWithTimeInterval:1

                                                  target:self

                                                selector:@selector(timeOut:)

                                                userInfo:nil

                                                 repeats:YES];

    }

    

}

- (void)stopTimer

{

    if (_timer) {

        [_timer invalidate];

        _timer = nil;

        _timerInterval = 0;

    }

    [self updateButtonState];

}

- (void)timeOut:(NSTimer *)timer

{

    _timerInterval--;

    if (_timerInterval > 0) {

    }

    else {

        [self stopTimer];

    }

    [self updateButtonState];

}

- (void)setFormatString:(NSString *)formatString

{

    _formatString = formatString;

}

- (void)updateButtonState

{

    if (_timerInterval > 0) {

        [self setTitle:[NSString stringWithFormat:@"%d", _timerInterval] forState:UIControlStateDisabled];

    }

    else {

        [self setTitle:@"验证" forState:UIControlStateNormal];

        self.enabled = YES;

    }

}

标记***的为重点知识,设置按钮的什么状态就要再什么状态下更改按钮的文字,颜色或者背景图片等。

调了n长时间终于调试出来了,哎,自己粗心大意了。。。

《自定义计时器UIButton.doc》

下载本文的Word格式文档,以方便收藏与打印。