1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftUIでのTimerの使い方ガイド【初心者向け】

Posted at

そもそもTimerとは?

Timer は一定時間ごとに処理を発生させるための仕組みです。
例えば、1秒ごとにカウントダウンしたり、時刻を表示したりするときに使うことができます!

基本的な使い方(SwiftUI)

例:1秒ごとにカウントアップするタイマー

import SwiftUI

struct TimerView: View {
    @State var counter = 0

    // 1秒ごとにタイマーを発行
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        VStack(spacing: 20) {
            Text("カウント: \(counter)")
                .font(.largeTitle)
            
            Button("リセット") {
                counter = 0
            }
        }
        // タイマーが処理するたびにカウントを増やす
        .onReceive(timer) { _ in
            counter += 1
        }
    }
}

Timerを止めたい場合

Timer は autoconnect() によって自動的にスタートしますが、止めたり再開したいときは、.connect() や .upstream.connect().cancel() を使います。

import SwiftUI
import Combine

struct ControllableTimerView: View {
    @State var counter = 0
    @State var isRunning = false

    let timer = Timer.publish(every: 1, on: .main, in: .common)
    @State var cancellable: Cancellable?

    var body: some View {
        VStack(spacing: 20) {
            Text("カウント: \(counter)")
                .font(.largeTitle)

            HStack {
                Button(isRunning ? "ストップ" : "スタート") {
                    if isRunning {
                        cancellable?.cancel()
                    } else {
                        cancellable = timer.connect()
                    }
                    isRunning.toggle()
                }

                Button("リセット") {
                    counter = 0
                }
            }
        }
        .onReceive(timer) { _ in
            if isRunning {
                counter += 1
            }
        }
    }
}

まとめ

操作 方法
一定間隔で処理を実行 Timer.publish + .onReceive
自動スタート .autoconnect()
手動で開始・停止 .connect() / .cancel()
状態の制御 @State@StateObjectなどで管理

ぜひアプリ開発でタイマーを導入する際はこの記事を参考にしてみてください!✌️

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?