如何显示所选切换的数量

问题描述 投票:0回答:1

@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
    }
}
math swiftui toggle
1个回答
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

然后,您可以在下一步中提取切换并将其切换到可重复使用的子视图
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.