SwiftUI: Flip flop game using grid and animation

Monika Tamrakar
2 min readAug 4, 2020

--

SwiftUI 2.0 have a lot of new components like Grid, Map, TextEditor, TabView. Here we’ll learn about grid, navigation, environmentObject, timer and animation. Let’s get started…

Swift Grid

The following code shows how we can create grid with minimum column width. It automatically adjusts no of column in one row.

let columns = [GridItem(.adaptive(minimum: 80))]LazyVGrid(columns: columns, spacing: 10) {
ForEach(model.allCards) { card in
CardView(selection: card, count:$count)
.environmentObject(model).cornerRadius(10)
}
}

EnvironmentObject

@EnvironmentObject is used for data that should be shared with all the views in app, ensuring that views are automatically updated if data is changed.

var body: some Scene {WindowGroup {
ContentView().environmentObject(CardModel())
}
}

We can use that object like this

struct ContentView: View {@EnvironmentObject private var model: CardModel
var body: some View {
if model.allCards.filter({$0.isFlip == false}).count == 0 {
withAnimation {
CompletedView()
}
}
}

Timer

We will use timer to display time in app, but you can use timer to schedule any work after some seconds either once or repeatedly.

let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()@State private var time = 0Text("Time \(((time % 3600) / 60)) : \((time % 3600) % 60)").onReceive(timer) { val in
time += 1
}

Animation

The following code shows how we can use scale ease out animation.

VStack{
Text("You did it !!!!").font(.system(size: 25))
.foregroundColor(.orange).frame(width: 200, height: 200, alignment: .center)
}
.background(Color.white).frame(width: 200, height: 200)
.scaleEffect(showMsg ? 1 : 0)
.cornerRadius(100)
.shadow(color: .orange, radius: 100, x: 1, y: 1)
.animation(Animation.easeInOut(duration: 0.5).delay(0.1))
.onAppear() {
self.showMsg.toggle()
}

Conclusion

So, we built a flip flop game using grid, environmentObject and also showed scale ease out animation with shadow.

That’s it for this. You can check whole project on https://github.com/monika-tamrakar/SwiftUI-2.0-flip-flop.

Thanks for reading 😊.

--

--