How do you make an count-up timer in Objective-C?

2019-04-14 20:13发布

I have looked everywhere but I cannot find out how to do so. I need a simple timer that can count up in milliseconds and can be stopped. (XCode 3.1, Objective-C, iPhone OS Development)

4条回答
Evening l夕情丶
2楼-- · 2019-04-14 21:04

Here is the sample code which i have done one timer with minute, second, and mili seconds.. So, its helpful for you. And also do it release after not use..

-(void)showTime:(NSTimer *)sender
    {
        miniSeconds++;
        if (miniSeconds == 10)
        {
            miniSeconds = 0;
            seconds++;
            if (seconds == 60)
            {
                seconds = 0;
                minutes++;
            }
        }
        timeLabel.text = [NSString stringWithFormat:@"%02i:%02i:%02i",minutes,seconds,miniSeconds];
    }
    -(void)nextLevelTime
    {
        [labelTimer invalidate];
        miniSeconds = 0;
        seconds = 0;
        minutes = 0;
    }

The nextLevel method use for to stop timer and release all thing..

Use it, I have done with this code..

查看更多
【Aperson】
3楼-- · 2019-04-14 21:05

Am I just being daft or is "count-up timer" the same as a stopwatch.

If it is, check out this video tutorial

查看更多
叛逆
4楼-- · 2019-04-14 21:08
ら.Afraid
5楼-- · 2019-04-14 21:10
@interface ViewController()
{
UILabel *progress;
    NSTimer *timer;
    int currMinute;
    int currSeconds;
    int currHours;
}
@end


@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    progress=[[UILabel alloc] initWithFrame:CGRectMake(80, 15, 100, 50)];
    progress.textColor=[UIColor redColor];
    [progress setText:@"Time : 00:00:00"];
    progress.backgroundColor=[UIColor clearColor];
    [self.view addSubview:progress];
    currMinute=00;
    currSeconds=00;
    currHours=00;

    // Do any additional setup after loading the view, typically from a nib.
}
-(void)start
{
    timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];

}
-(void)timerFired
{
    currSeconds+=1;
    if(currSeconds==60)
    {
        currSeconds=0;
        currMinute+=1;
        if(currMinute==60)
        {
            currMinute=0;
            currHours+=1;

        }
    }
    [_progress setText:[NSString stringWithFormat:@"%@%02d%@%02d%@%02d",@"Time : ",currHours,@":",currMinute,@":",currSeconds]];

    if(currMinute==2)//stop at 2 minute
    {
        [timer invalidate];
    }
}
查看更多
登录 后发表回答