I've worked through Apple's dice demo for SwiftUI, so far so good. I've got a single Die view with a button to "roll" the die. This works perfectly using the code below:
struct DieView: View {
init(dieType: DieType) {
self.dieValue = Int.random(in: 1...dieType.rawValue)
self.dieType = dieType
}
@State private var dieValue: Int
@State private var dieType: DieType
var body: some View {
VStack {
if self.dieType == DieType.D6 {
Image(systemName: "die.face.\(dieValue)")
.resizable()
.frame(width: 100, height: 100)
.padding()
}
else {//self.dieType == DieType.D12{
Text("\(self.dieValue)")
.font(.largeTitle)
}
Button("Roll"){
withAnimation{
dieValue = Int.random(in: 1...dieType.rawValue)
}
}
.buttonStyle(.bordered)
}
Spacer()
}
}
Now I want to do a DiceSetView with an arbitrary number of dice. I've got the UI working with the following;
struct DiceSetView: View {
@State private var totalScore: Int = 0
var body: some View {
ScrollView(.horizontal) {
HStack{
DieView(dieType: DieType.D6)
DieView(dieType: DieType.D6)
DieView(dieType: DieType.D6)
}
}
HStack{
Button("Roll All"){}
.buttonStyle(.bordered)
Text("Score \(totalScore)")
.font(.callout)
}
Spacer()
}
}
Where I'm struggling is how to get the total of all the dice in a set and to roll all the dice in a set on a button click.
I can't iterate through the dice, and just "click" the buttons in the child views from their parents, and I can't think how it should be structured to achieve this (I'm new to this style of programming!) - can anyone point me in the right direction for how to achieve what I want? I realise that I'm probably missing something fundamentally conceptual here....
Topic:
UI Frameworks
SubTopic:
SwiftUI