iOSアプリ開発の初心者向けに、基本的なコードで作ることができる「ストップウォッチアプリ」の作成方法を紹介します。
本記事では以下の内容が学べます。
・ボタンの作成
・カウントアップの実装方法
・ボタンタップ時のイベント設定
それでは解説していきます。
①スタートを押すとカウントアップが始まり、停止ボタンが表示される
②停止ボタンを押すとカウントアップが止まり、再スタートおよび終了ボタンが表示される
Xcode Version 12.5 (12E262)
Apple Watch Ver.7.4.1(18T201)
iPhone X Ver.14.5.1 
Xcodeを立ち上げ、iOS App With Watch Appを選択します。
Product Nameにアプリのタイトルを入力します。今回はStopwatch-sampleとしました。
プロジェクトが立ち上がったらStopwatch-sample WatchKit Extension フォルダ内のContentView.swiftを選択します。
右上の「Resume」を押してApple Watchの画面が表示されることを確認してください。
ContentView.swiftの中身を書いていきます。
//
//  ContentView.swift
//  Stopwatch-sample WatchKit Extension
//
//  Created on 2021/05/22.
//
import SwiftUI
struct ContentView: View {
    @ObservedObject var stopWatchManeger = StopWatchManeger()
    
    var body: some View {
        VStack {
            Text(String(format:"%.1f",stopWatchManeger.secondsElapsed))
                .font(.custom("Futura", size: 50))
            
            if stopWatchManeger.mode == .stop{
                Button(action: {self.stopWatchManeger.start()}){
                Text("スタート").font(.title)
                }
            }
            
            if stopWatchManeger.mode == .start{
                Button(action: {self.stopWatchManeger.pause()}){
                    Text("停止").font(.title)
                }
                
            }
                
            if stopWatchManeger.mode == .pause{
                VStack{
                    Button(action: {self.stopWatchManeger.start()}){
                    Text("再スタート").font(.body)
                           }
                    Button(action: {self.stopWatchManeger.stop()}){
                    Text("終了").font(.body)
                           }
                }
            }
        }
     }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
struct ExtractedView: View {
    var label:String
    var buttonColor:Color
    var textColor:Color
    
    var body: some View {
        Text(label)
            .foregroundColor(textColor)
            .background(buttonColor)
    }
}
class StopWatchManeger:ObservableObject{
    
    enum stopWatchMode{
        case start
        case stop
        case pause
    }
    
    @Published var mode:stopWatchMode = .stop
    
    @Published var secondsElapsed = 0.0
    var timer = Timer()
    
    func start(){
        mode = .start
        timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true){ timer in
            self.secondsElapsed += 0.1
        }
    }
    
    func stop(){
        timer.invalidate()
        secondsElapsed = 0
        mode = .stop
    }
    
    func pause(){
         timer.invalidate()
        mode = .pause
     }
}