iOS Development - Timer App

Here, we are going to make a Timer app for an iOS, using Swift 3 and Xcode 8.

Open Xcode and create a new Single View Application and name it Timer (You can name it anything you like).

 

 
 

Click Main.StoryBoard.
 

Add a label to display the seconds (We are going to set 240 as default ). Resize it in Properties menu.

 

Add a navigation bar to the top and change the title of Timer.

 

Add two Bar buttons on the top navigation bar and change the System Item into play and pause.

 

Add a Toolbar to the bottom and rename the item to “-10”.

 

Add two bar button items and name them “Reset “and “+10”.

 

Click ViewController.Swift.



Now, control + drag label to the program and name it “timerLabel”.

Control + drag each button to the code and name them “play”,”pause”,”minusTen”,”plusTen”,”resetTimer”(Connection type must be Button).

Edit the code, as given below.

  1. import UIKit  
  2. class ViewController: UIViewController {  
  3.     var timer = Timer()  
  4.     var time = 240  
  5.     func decreaseTimer() {  
  6.         if time > 0 {  
  7.             time = time - 1  
  8.             timerLabel.text = String(time)  
  9.         } else {  
  10.             timer.invalidate()  
  11.         }  
  12.     }  
  13.     @IBOutlet weak  
  14.     var timerLabel: UILabel!@IBAction func play(_ sender: Any) {  
  15.         timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.decreaseTimer), userInfo: nil, repeats: true)  
  16.     }  
  17.     @IBAction func pause(_ sender: Any) {  
  18.         timer.invalidate()  
  19.     }  
  20.     @IBAction func minusTen(_ sender: Any) {  
  21.         if time > 10 {  
  22.             time -= 10  
  23.             timerLabel.text = String(time)  
  24.         }  
  25.     }  
  26.     @IBAction func plusTen(_ sender: Any) {  
  27.         time += 10  
  28.         timerLabel.text = String(time)  
  29.     }  
  30.     @IBAction func resetTimer(_ sender: Any) {  
  31.         time = 240  
  32.         timerLabel.text = String(time)  
  33.     }  
  34.     override func viewDidLoad() {  
  35.         super.viewDidLoad()  
  36.         // Do any additional setup after loading the view, typically from a nib.  
  37.     }  
  38.     override func didReceiveMemoryWarning() {  
  39.         super.didReceiveMemoryWarning()  
  40.         // Dispose of any resources that can be recreated.  
  41.     }  
  42. }   

Now, run the app.

Ebook Download
View all
Learn
View all