Post

Replies

Boosts

Views

Created

Multiple buttons - repetitive code
I have made a custom button in its own struct. I have inserted 5 of them into the ContentView body. Is there a better way to code the buttons into ContentView? It seems to be repetitive. Thanks for any assistance. struct ContentView: View { @State private var score = 0 var body: some View { ZStack { Color.pink.opacity(0.2).ignoresSafeArea() VStack { Spacer() Text("Keep Score") .foregroundStyle(.black) .font(.system(size: 50, weight: .semibold, design: .rounded)) Spacer() Text("The score is: \(score)") .foregroundStyle(.secondary) .font(.system(size: 30, weight: .semibold, design: .rounded)) Spacer() ButtonView(name: "Add 1", background: .red) { score += 1 } ButtonView(name: "Add 2", background: .green) { score += 2 } ButtonView(name: "Add 3", background: .yellow) { score += 3 } ButtonView(name: "Minus 1", background: .cyan) { score -= 1 } ButtonView(name: "Reset", background: .mint) { score = 0 } } Spacer() } } } struct ButtonView: View { let name: String let background: Color let action: () -> Void var body: some View { Button { action() } label: { ZStack { RoundedRectangle(cornerRadius: 5) .stroke(lineWidth: 4) .foregroundColor(.black) RoundedRectangle(cornerRadius: 5) .foregroundColor(background) Text(name) .foregroundStyle(.black).bold().font(.subheadline) } } .padding(5) .frame(width: 75, height: 50) } }
3
0
494
Feb ’24