Hi All,
I've got a skeleton of an app, but it's not quite working yet.
I have a view that should display a list of past dice rolls. it's using a ForEach
in a List
. But the List
is always empty.
I am uncertain what I have setup incorrectly, I am not sure if it's my view or my data model. See below or the gitHub link
DiceRolls.swift
The data model
import SwiftUI
struct SingleDiceRoll: Identifiable, Codable, Hashable {
let id = UUID()
let dice1: Int
let dice2: Int
}
class DiceRolls: ObservableObject {
@Published var multipleDiceRolls: [SingleDiceRoll]
init() {
multipleDiceRolls = []
}
}
PastRollsView.swift
list view of previous dice rolls
import SwiftUI
struct PastRollsView: View {
@ObservedObject var diceRolls: DiceRolls
var body: some View {
List {
ForEach(diceRolls.multipleDiceRolls) { roll in
Text("Foo \(roll.dice1)")
}
}
}
}
struct PastRollsView_Previews: PreviewProvider {
static var previews: some View {
PastRollsView(diceRolls: DiceRolls())
}
}
ContentView.swift
View to roll dice and see current roll
import SwiftUI
struct ContentView: View {
@State private var dieOne = 0
@State private var dieTwo = 0
@ObservedObject var diceRolls: DiceRolls
var body: some View {
VStack {
Button(action: rollDice, label: { Text("Roll Dice")})
.padding()
Text("Dice One: \(dieOne)")
.padding()
Text("Dice Two: \(dieTwo)")
}
}
func rollDice() {
let dice1 = Int.random(in: 1...6)
let dice2 = Int.random(in: 1...6)
dieOne = dice1
dieTwo = dice2
diceRolls.multipleDiceRolls.append(SingleDiceRoll(dice1: dice1, dice2: dice2))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(diceRolls: DiceRolls())
}
}
MainTabView.swift
A TabView controller
import SwiftUI
enum Tab {
case rollView, pastRollView
}
struct MainTabView: View {
@State private var selectedTab = Tab.rollView
@ObservedObject var diceRolls: DiceRolls
var body: some View {
TabView {
ContentView(diceRolls: DiceRolls())
.tabItem {
Image(systemName: "gamecontroller")
Text("Roll Dice")
}
.tag(Tab.rollView)
PastRollsView(diceRolls: diceRolls)
.tabItem {
Image(systemName: "list.dash")
Text("past rolls")
}
.tag(Tab.pastRollView)
}
}
}
struct MainTabView_Previews: PreviewProvider {
static var previews: some View {
MainTabView(diceRolls: DiceRolls())
}
}