krz/daybyday

iOS learning games for young children: days, months, seasons, numbers, letters, animals and more. education ios kids swift https://krz.sh/apps/daybyday/

DayByDay/Mascot/GameMascot.swift

main
daybyday/DayByDay/Mascot/GameMascot.swift history · blame · raw

30 lines · 844 bytes

2 symbols in this file
 1//
 2//  GameMascot.swift
 3//  DayByDay
 4//
 5
 6import SwiftUI
 7
 8/// A game's mascot, small enough to sit beside "Hear it again". Puts the
 9/// mood back to idle once it has held.
10struct GameMascot: View {
11    @Binding var state: MascotState
12
13    /// Bumped when the mascot goes away, so a pending settle does nothing.
14    @State private var generation = 0
15
16    var body: some View {
17        MascotView(mood: state.mood)
18            .frame(width: 64, height: 64)
19            .onAppear(perform: scheduleSettle)
20            .onChange(of: state.ticket, scheduleSettle)
21            .onDisappear { generation += 1 }
22    }
23
24    private func scheduleSettle() {
25        let ticket = state.ticket, gen = generation
26        DispatchQueue.main.asyncAfter(deadline: .now() + state.hold) {
27            if gen == generation { state.settle(ticket) }
28        }
29    }
30}