ghard123
(Greg)
1
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.
import SwiftUI
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()
Group {
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 {
VStack {
Button {
action()
} label: {
ZStack {
RoundedRectangle(cornerRadius: 10)
.stroke(lineWidth: 6)
.foregroundColor(.black)
RoundedRectangle(cornerRadius: 10)
.foregroundColor(background)
Text(name)
.foregroundStyle(.black).bold().font(.headline)
}
}
.padding(5)
.frame(width: 150, height: 50)
}
}
}
RJ_Clegg
(Robert J Clegg)
2
At first glance; you could put the button titles and their colors into a collection (Maybe a dictionary) and then iterate over that in a ForEach loop to create a button, setting it's title and color, in the Group
Pippin
(Ethan Pippin)
3
You will want to take a look at creating a custom ButtonStyle. You also don't need to nest them within a Group, there are no modifiers being applied, and the VStack in ButtonView is unnecessary. Lastly, don't worry about repetition if you need to declare that those are the buttons/views that you need, especially since they differ in a few ways.
Also the obligatory: these are the forums for the Swift programming language and SwiftUI questions should be asked on Apple's developer forums.