How To Become A Programmer Without A Degree & Experience

[ iOS ] How to create a Stopwatch

iOS (Objective-C) Tutorial – How to Create a Stopwatch –

iOS (Objective-C) Tutorial  - How to Create a Stopwatch -

 

 

Introduction

In this video, I’ll show you how to create a stopwatch app.

It’s the simple app, but it includes a very important class, NSTimer.

Hope you like this stopwatch app 🙂

 

screen

 

I set font and colors as follows. (You can check them in the video.)

Font(size)@property
00:00:00Verdana (48)timerLabel
StartVerdana (16)startBtn
ResetVerdana (16)resetBtn
Color
Navy#34495E
Red#F26058

 

 

Sample Code

//
//  ViewController.h
//  stopwatch
//
 
#import <UIKit/UIKit.h>
 
@interface ViewController : UIViewController
{
    NSTimer *myTimer;
    BOOL running;
    int count;
}
 
 
@property (weak, nonatomic) IBOutlet UILabel *timerLabel;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
@property (weak, nonatomic) IBOutlet UIButton *resetBtn;
 
- (IBAction)startBtnPushed:(id)sender;
- (IBAction)resetBtnPushed:(id)sender;
 
- (void)updateTimer;
 
@end
//
//  ViewController.m
//  stopwatch
//
 
#import "ViewController.h"
 
@interface ViewController ()
 
@end
 
@implementation ViewController
@synthesize timerLabel,startBtn,resetBtn;
 
- (void)viewDidLoad {
    [super viewDidLoad];
    
    running = NO;
    count = 0;
    timerLabel.text = @"00:00.00";
    
    startBtn.layer.cornerRadius = 45;
    resetBtn.layer.cornerRadius = 45;
    
}
 
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
 
- (IBAction)startBtnPushed:(id)sender {
    
    if (running == NO) {
        running = YES;
        [startBtn setTitle:@"STOP" forState:UIControlStateNormal];
        
        if (myTimer == nil) {
            
            myTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
            
        }
        
    } else {
        
        [self stopTimer];
        
    }
    
    
}
 
- (IBAction)resetBtnPushed:(id)sender {
    
    [self stopTimer];
    
    count = 0;
    timerLabel.text = @"00:00.00";
    
}
 
- (void)stopTimer {
    
    running = NO;
    [myTimer invalidate];
    myTimer = nil;
    [startBtn setTitle:@"START" forState:UIControlStateNormal];
    
}
 
- (void)updateTimer {
    
    count++;
    
    int min = floor(count/100/60);
    int sec = floor(count/100);
    int mSec = count % 100;
    
    if (sec >= 60) {
        sec = sec % 60;
    }
    
    timerLabel.text = [NSString stringWithFormat:@"%02d:%02d.%02d",min,sec,mSec];
}
 
@end