@State private var elderly = false
@State private var immobility = false
@State private var cancer = false
var body: some View {
VStack {
Toggle(isOn: $elderly) {
Text("> 65")
}
.padding()
Toggle(isOn: $immobility) {
Text("Immobility")
}
.padding()
Toggle(isOn: $cancer) {
Text("Cancer")
}
.padding()
Button {
// action that adds the points
} label: {
Text("Calculate")
}
.fontWeight(.bold)
.frame(width: 200.0, height: 50)
.background(Color.blue)
.cornerRadius(10)
.foregroundColor(.white)
.font(.system(size: 20))
.padding()
}
}
您可以创建一个自定义结构,该结构同时保留toggle状态和每个类型的点值
struct TogglePoints: Equatable {
let id = UUID()
var toggle: Bool
let points: Int
var pointsValue: Int {
toggle ? points : 0
}
}
@State private var elderly = TogglePoints(toggle: false, points: 1)
@State private var immobility = TogglePoints(toggle: false, points: 2)
@State private var cancer = TogglePoints(toggle: false, points: 3)
var body: some View {
VStack {
Toggle(isOn: $elderly.toggle) {
Text("> 65")
}
.padding()
.onChange(of: elderly) {
points = elderly.pointsValue + immobility.pointsValue + cancer.pointsValue
}
// and so on for the other toggle properties