6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftでStopWatchを作ってみた

Last updated at Posted at 2016-10-15

この動画↓

SwiftでなんちゃってStopWatchを作ってみた(その1)http://www.nicovideo.jp/watch/sm24733337
SwiftでなんちゃってStopWatchを作ってみた(その2)http://www.nicovideo.jp/watch/sm24739192

を参考にStopWatchアプリを作ってみた。

挙動こんな感じ
StopWatch - Swift
https://youtu.be/5pcY_DGGPeY

動画通りに作ってもバージョンの違いで最初はエラー、ビルド通っても動かずなど色々ありましたが、試行錯誤したソースコードが後述のものです。

ちなみに、

swift 2.2
Xcode 7.3.1

で作成しました。

後から色々機能を付け足すつもりでプロジェクトをタブバーアプリケーションで作成したため、
関数呼び出し時にクラス名も記述している箇所などはバージョン云々ではなく書き方が違うと思うのですが、
細かいところがいくつか違うのでご参考までに。

import UIKit

class FirstViewController: UIViewController {

var countNum = 0
var timerRunning = false
var timer = NSTimer()

func update(){
    countNum+=1
    let ms = countNum % 100
    let s = (countNum - ms) / 100 % 60
    let m = (countNum - s - ms) / 6000 % 3600
    label.text = String (format: "%02d:%02d.%02d", m,s,ms)
}
    
    
    @IBOutlet weak var label: UILabel!
    
    @IBAction func start(sender: UIButton) {
        if timerRunning == false{
            timer =
                NSTimer.scheduledTimerWithTimeInterval(0.01,
                                                      target:self,
                                                      selector: #selector(FirstViewController.update),
                                                      userInfo: nil,
                                                      repeats: true)
           timerRunning = true
        }
        
        
    }
    
    @IBAction func stop(sender: UIButton) {
        if timerRunning == true{
            timer.invalidate()
            timerRunning = false
        }
        
        
    }
    
    @IBAction func reset(sender: UIButton) {
        countNum = 0
        label.text = "00:00.00"
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?