今回はタイマーについてです.
環境は,
- macOS Catalina 10.15.7
- Xcode 12.0.1
- Swift 5.3
- iOS 14.0
です.
目次
Timerとは
Timerの基本的なinitializer
init(timeInterval interval: TimeInterval,
repeats: Bool,
block: @escaping (Timer) -> Void)
- interval:タイマーの間隔を指定します.
- repeats:タイマーの繰り返し設定ができます. Bool値をとります.
- block:タイマーが起動したときに実行されるアクションを記述します.
block
Timerの基本的なメソッド
class func scheduledTimer(withTimeInterval interval: TimeInterval,
repeats: Bool,
block: @escaping (Timer) -> Void) -> Timer
- interval:タイマーの間隔を指定します.
- repeats:タイマーの繰り返し設定ができます. Bool値をとります.
- block:タイマーが起動したときに実行されるアクションを記述します.
block
メソッド | 説明 |
---|---|
scheduledTimer() | タイマーを作成します |
invalidate() | タイマーを終了します |
fire() | 任意のタイミングでタイマーを呼び出します |
Timerの具体例(Playground編)
3秒間待つ
Playgroundで3秒間待つコードを書いています.
import Foundation
print("3秒間待ちます...")
Timer.scheduledTimer(withTimeInterval: 3.0, repeats: false) { (timer)
in
print("3秒経ちました!")
}

カウントダウン!
import Foundation
var counter = 10
func report(timer: Timer) {
print("\(counter) 秒")
counter -= 1
if counter < 0 {
print("終了!")
timer.invalidate()
}
}
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) {
(timer) in
report(timer: timer)
}

Timerの具体例
一定時間ごとにランダムな数を出力する
import SwiftUI
struct ContentView: View {
@State var timer: Timer?
@State var randomNumber = 0
var body: some View {
VStack(spacing: 50) {
HStack(spacing: 50) {
Button(action: {
self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true){_ in
randomNumber = Int.random(in: 1..<100)
}
}) {
Text("Start")
}
Button(action: { self.timer?.invalidate() }) {
Text("Stop")
}
}
Text("\(randomNumber)")
}
.font(.title)
}
}

一定時間ごとにボタンの色を変える
import SwiftUI
struct ContentView: View {
@State var timer: Timer?
@State var randomNumber = 0
@State private var redRatio = 0.0
@State private var greenRatio = 1.0
@State private var blueRatio = 1.0
@State private var opacity = 1.0
var body: some View {
VStack(spacing: 50) {
HStack(spacing: 100) {
Button(action: {
self.timer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true){_ in
randomNumber = Int.random(in: 1..<100)
redRatio = Double.random(in: 0...1)
greenRatio = Double.random(in: 0...1)
blueRatio = Double.random(in: 0...1)
}
}) {
Text("Start")
}
Button(action: { self.timer?.invalidate() }) {
Text("Stop")
}
}
Button(action: {}) {
Text("\(randomNumber)")
}
.frame(width: 150)
.background(Color(red: redRatio, green: greenRatio, blue: blueRatio, opacity: opacity))
.cornerRadius(5)
.overlay(RoundedRectangle(cornerRadius: 5)
.stroke(Color.black, lineWidth: 1))
.font(.largeTitle)
}
}
}

7個の中から選ぶ
7個の中からルーレットのようにランダムなものを選ぶアプリを作りました.
import SwiftUI
struct ContentView: View {
@State var timer: Timer?
@State var colorBase = Color.blue
@State var colorOther = Color.pink
@State var randomNumber = 4
var body: some View {
VStack(spacing: 30) {
HStack(spacing: 50) {
Button(action: {
self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true){_ in
randomNumber = Int.random(in: 1...7)
}
}) {
Text("Start")
}
Button(action: { self.timer?.invalidate() }) {
Text("Stop")
}
}
Text("あたなが選んだものは左から \(randomNumber) 番目です")
HStack {
ForEach(1..<randomNumber, id: \.self) { _ in
HStack(spacing: 10) {
CustomButton(color: colorBase)
}
}
CustomButton(color: colorOther)
ForEach(randomNumber..<7, id: \.self) { _ in
HStack(spacing: 10) {
CustomButton(color: colorBase)
}
}
}
}
}
}
struct CustomButton: View {
@State var color: Color
var body: some View {
Button(action:{
})
{
Text("A")
}
.padding(5)
.frame(width: 50)
.foregroundColor(Color.white)
.background(color)
.cornerRadius(5)
.overlay(RoundedRectangle(cornerRadius: 5)
.stroke(Color.black, lineWidth: 1))
}
}

円が大きくなるアニメーション
簡単な図形のアニメーションを作成してみました. 徐々に円が大きくなっていくものです.
import SwiftUI
struct ContentView: View {
@State var timer: Timer?
@State var radius: CGFloat = 10.0
var body: some View {
HStack(spacing: 50) {
Button(action: {
self.timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true){_ in
radius += 1
}
}) { Text("Start") }
Button(action: { self.timer?.invalidate() }) { Text("Stop") }
Button(action: { radius = 10.0 }) { Text("Reset") }
}
Circle()
.fill(Color.pink)
.frame(width: radius)
}
}

コメント