最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

swift - Is there a way where I press a button and it performs a calculation based on user inputs and displays texts to describe

programmeradmin0浏览0评论

I'm really new to coding (3 days to be exact). I'm trying to create an app that performs calculation based on user inputs.

So far, I managed to do that with success. When the button is clicked, it displays the result as expected.

However, I want to take it to another step by displaying a separate text that interprets the meaning of the result.

The result is Double, and I want to have 2 conditions. If it is < 0.5, it says XXX, otherwise YYY.

This is my code:

import SwiftUI
struct ContentView: View {
    enum FocusedField {
        case int
    }
    
    @FocusState private var focusedField: FocusedField?
    @State var HPEEP: String = ""
    @State var SetVT: String = ""
    @State var VTHPEEP: String = ""
    @State var LPEEP: String = ""
    @State var VTtotal: String = ""
    @State var Pplat: String = ""
    @State var answer: String = ""
    @State private var showMenu: Bool = false

    var body: some View {
        NavigationView {
            ZStack {
                Color(.mint)
                    .ignoresSafeArea(.all, edges: . all)
                ScrollView {
                    VStack {
                        HStack {
                            Text("High PEEP")
                                .font(.callout)
                                .padding()
                            Spacer()
                            TextField("cmH2O", text: $HPEEP)
                                .keyboardType(.numberPad)
                                .ignoresSafeArea(.keyboard)
                                .focused($focusedField, equals: .int)
                                .textFieldStyle(.roundedBorder)
                                .frame(width: 80)
                                .padding()
                                .cornerRadius(40)
                        }
                        HStack {
                            Text("Set Tidal Volue")
                                .font(.callout)
                                .padding()
                            Spacer()
                            TextField("ml", text: $SetVT)
                                .keyboardType(.numberPad)
                                .focused($focusedField, equals: .int)
                                .textFieldStyle(.roundedBorder)
                                .frame(width: 80)
                                .padding()
                                .cornerRadius(40)
                        }
                        
                        HStack {
                            Text("Exhaled Tidal Volume at High PEEP")
                                .font(.callout)
                                .padding()
                            Spacer()
                            TextField("ml", text: $VTHPEEP)
                                .keyboardType(.numberPad)
                                .focused($focusedField, equals: .int)
                                .textFieldStyle(.roundedBorder)
                                .frame(width: 80)
                                .padding()
                                .cornerRadius(40)
                        }
                        
                        HStack {
                            Text("Low PEEP")
                                .font(.callout)
                                .padding()
                            Spacer()
                            TextField("cmH2O", text: $LPEEP)
                                .keyboardType(.numberPad)
                                .focused($focusedField, equals: .int)
                                .textFieldStyle(.roundedBorder)
                                .frame(width: 80)
                                .padding()
                                .cornerRadius(40)
                        }
                        
                        HStack {
                            Text("Exhaled Tidal Volume from High to Low PEEP")
                                .font(.callout)
                                .padding()

                            Spacer()
                            TextField("ml", text: $VTtotal)
                                .keyboardType(.numberPad)
                                .focused($focusedField, equals: .int)
                                .textFieldStyle(.roundedBorder)
                                .frame(width: 80)
                                .padding()
                                .cornerRadius(40)
                        }
                        
                        HStack {
                            Text("Plateau Pressure at Low PEEP")
                                .font(.callout)
                                .padding()
                            Spacer()
                            TextField("cmH2O", text: $Pplat)
                                .keyboardType(.numberPad)
                                .focused($focusedField, equals: .int)
                                .textFieldStyle(.roundedBorder)
                                .frame(width: 80)
                                .padding()
                                .cornerRadius(40)
                        }
                        
                        Button {
                            // button action
                            let Cbaby = Double(SetVT)! / (Double(Pplat)! - Double(LPEEP)!)
                            let pVrec = Double(HPEEP)! - Double(LPEEP)!
                            let ppVrec = pVrec * Cbaby
                            let Vrec = Double(VTtotal)! - Double(VTHPEEP)! - ppVrec
                            let Crec = Vrec / (Double(HPEEP)! - Double(LPEEP)!)
                            let raw = max(Crec / Cbaby, 0)
                            
                            answer = String(format: "%.2f", raw)
                        } label: {
                            Text("Calculate")
                                .fontWeight(.bold)
                                .frame(width: 200.0, height: 50)
                                .background(Color.blue)
                                .cornerRadius(10)
                                .foregroundColor(.white)
                                .font(.system(size: 20))
                                .padding()
                        }
                        
                        Text("RI = \(answer)")
                            .font(.system(size: 20))
                            .fontWeight(.bold)
                        Spacer()
                    }
                }
                
                .navigationTitle("Recruitability")
                .navigationBarTitleDisplayMode(.inline)
                .toolbar {
                    ToolbarItem(placement: .keyboard) {
                        Spacer()
                    }
                    ToolbarItem(placement: .keyboard) {
                        Button {
                            focusedField = nil
                        } label: {
                            Image(systemName: "keyboard.chevronpact.down")
                        }
                    }
                }

                .toolbar {
                    Button {
                        self.showMenu.toggle()
                    } label: {
                        if showMenu {
                            Image(systemName: "xmark")
                                .foregroundColor(Color.orange)

                        } else {
                            Image(systemName: "text.justify")
                                .foregroundColor(Color.orange)
                        }
                    }
                }
            }
        }
    }
}

I'm really new to coding (3 days to be exact). I'm trying to create an app that performs calculation based on user inputs.

So far, I managed to do that with success. When the button is clicked, it displays the result as expected.

However, I want to take it to another step by displaying a separate text that interprets the meaning of the result.

The result is Double, and I want to have 2 conditions. If it is < 0.5, it says XXX, otherwise YYY.

This is my code:

import SwiftUI
struct ContentView: View {
    enum FocusedField {
        case int
    }
    
    @FocusState private var focusedField: FocusedField?
    @State var HPEEP: String = ""
    @State var SetVT: String = ""
    @State var VTHPEEP: String = ""
    @State var LPEEP: String = ""
    @State var VTtotal: String = ""
    @State var Pplat: String = ""
    @State var answer: String = ""
    @State private var showMenu: Bool = false

    var body: some View {
        NavigationView {
            ZStack {
                Color(.mint)
                    .ignoresSafeArea(.all, edges: . all)
                ScrollView {
                    VStack {
                        HStack {
                            Text("High PEEP")
                                .font(.callout)
                                .padding()
                            Spacer()
                            TextField("cmH2O", text: $HPEEP)
                                .keyboardType(.numberPad)
                                .ignoresSafeArea(.keyboard)
                                .focused($focusedField, equals: .int)
                                .textFieldStyle(.roundedBorder)
                                .frame(width: 80)
                                .padding()
                                .cornerRadius(40)
                        }
                        HStack {
                            Text("Set Tidal Volue")
                                .font(.callout)
                                .padding()
                            Spacer()
                            TextField("ml", text: $SetVT)
                                .keyboardType(.numberPad)
                                .focused($focusedField, equals: .int)
                                .textFieldStyle(.roundedBorder)
                                .frame(width: 80)
                                .padding()
                                .cornerRadius(40)
                        }
                        
                        HStack {
                            Text("Exhaled Tidal Volume at High PEEP")
                                .font(.callout)
                                .padding()
                            Spacer()
                            TextField("ml", text: $VTHPEEP)
                                .keyboardType(.numberPad)
                                .focused($focusedField, equals: .int)
                                .textFieldStyle(.roundedBorder)
                                .frame(width: 80)
                                .padding()
                                .cornerRadius(40)
                        }
                        
                        HStack {
                            Text("Low PEEP")
                                .font(.callout)
                                .padding()
                            Spacer()
                            TextField("cmH2O", text: $LPEEP)
                                .keyboardType(.numberPad)
                                .focused($focusedField, equals: .int)
                                .textFieldStyle(.roundedBorder)
                                .frame(width: 80)
                                .padding()
                                .cornerRadius(40)
                        }
                        
                        HStack {
                            Text("Exhaled Tidal Volume from High to Low PEEP")
                                .font(.callout)
                                .padding()

                            Spacer()
                            TextField("ml", text: $VTtotal)
                                .keyboardType(.numberPad)
                                .focused($focusedField, equals: .int)
                                .textFieldStyle(.roundedBorder)
                                .frame(width: 80)
                                .padding()
                                .cornerRadius(40)
                        }
                        
                        HStack {
                            Text("Plateau Pressure at Low PEEP")
                                .font(.callout)
                                .padding()
                            Spacer()
                            TextField("cmH2O", text: $Pplat)
                                .keyboardType(.numberPad)
                                .focused($focusedField, equals: .int)
                                .textFieldStyle(.roundedBorder)
                                .frame(width: 80)
                                .padding()
                                .cornerRadius(40)
                        }
                        
                        Button {
                            // button action
                            let Cbaby = Double(SetVT)! / (Double(Pplat)! - Double(LPEEP)!)
                            let pVrec = Double(HPEEP)! - Double(LPEEP)!
                            let ppVrec = pVrec * Cbaby
                            let Vrec = Double(VTtotal)! - Double(VTHPEEP)! - ppVrec
                            let Crec = Vrec / (Double(HPEEP)! - Double(LPEEP)!)
                            let raw = max(Crec / Cbaby, 0)
                            
                            answer = String(format: "%.2f", raw)
                        } label: {
                            Text("Calculate")
                                .fontWeight(.bold)
                                .frame(width: 200.0, height: 50)
                                .background(Color.blue)
                                .cornerRadius(10)
                                .foregroundColor(.white)
                                .font(.system(size: 20))
                                .padding()
                        }
                        
                        Text("RI = \(answer)")
                            .font(.system(size: 20))
                            .fontWeight(.bold)
                        Spacer()
                    }
                }
                
                .navigationTitle("Recruitability")
                .navigationBarTitleDisplayMode(.inline)
                .toolbar {
                    ToolbarItem(placement: .keyboard) {
                        Spacer()
                    }
                    ToolbarItem(placement: .keyboard) {
                        Button {
                            focusedField = nil
                        } label: {
                            Image(systemName: "keyboard.chevron.compact.down")
                        }
                    }
                }

                .toolbar {
                    Button {
                        self.showMenu.toggle()
                    } label: {
                        if showMenu {
                            Image(systemName: "xmark")
                                .foregroundColor(Color.orange)

                        } else {
                            Image(systemName: "text.justify")
                                .foregroundColor(Color.orange)
                        }
                    }
                }
            }
        }
    }
}
Share Improve this question edited 2 days ago dthorbur 1,0253 gold badges13 silver badges25 bronze badges asked Feb 6 at 12:21 Alfred WongAlfred Wong 212 bronze badges New contributor Alfred Wong is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Add a comment  | 

2 Answers 2

Reset to default 0

You can achieve this by adding another @State variable to store the interpretation text and updating it inside your button's action. Here's how you can modify your code:

@State var interpretation: String = ""  // New state variable for interpretation

Button {
    // Ensure all inputs are valid numbers
    if let setVT = Double(SetVT), let pplat = Double(Pplat),
       let lPEEP = Double(LPEEP), let hPEEP = Double(HPEEP),
       let vtTotal = Double(VTtotal), let vtHPEEP = Double(VTHPEEP) {

        let Cbaby = setVT / (pplat - lPEEP)
        let pVrec = hPEEP - lPEEP
        let ppVrec = pVrec * Cbaby
        let Vrec = vtTotal - vtHPEEP - ppVrec
        let Crec = Vrec / (hPEEP - lPEEP)
        let raw = max(Crec / Cbaby, 0)

        answer = String(format: "%.2f", raw)

        // Interpretation logic
        interpretation = raw < 0.5 ? "XXX" : "YYY"
    } else {
        answer = "Invalid input"
        interpretation = ""
    }
} label: {
    Text("Calculate")
        .fontWeight(.bold)
        .frame(width: 200.0, height: 50)
        .background(Color.blue)
        .cornerRadius(10)
        .foregroundColor(.white)
        .font(.system(size: 20))
        .padding()
}

// Display result and interpretation
Text("RI = \(answer)")
    .font(.system(size: 20))
    .fontWeight(.bold)

Text(interpretation)
    .font(.system(size: 18))
    .foregroundColor(.gray)

Explanation:

  1. Added @State var interpretation: String = "" to store the interpretation.
  2. Used a conditional (raw < 0.5 ? "XXX" : "YYY") to assign the appropriate interpretation.
  3. Handled invalid input cases to prevent crashes when the user enters non-numeric values.

Now, when the user clicks the button, the calculated result will be displayed along with a meaningful interpretation!

This one is going to be the reply to your comment:

You can handle multiple conditions using if-else or a switch statement. Also, for different text colors, you can use .foregroundColor() with a corresponding Color value.

Here's how you can update the code to accommodate multiple conditions and different text colors:

@State var interpretation: String = ""  // For interpretation text
@State var interpretationColor: Color = .gray  // For dynamic text color

Button {
    // Ensure all inputs are valid numbers
    if let setVT = Double(SetVT), let pplat = Double(Pplat),
       let lPEEP = Double(LPEEP), let hPEEP = Double(HPEEP),
       let vtTotal = Double(VTtotal), let vtHPEEP = Double(VTHPEEP) {

        let Cbaby = setVT / (pplat - lPEEP)
        let pVrec = hPEEP - lPEEP
        let ppVrec = pVrec * Cbaby
        let Vrec = vtTotal - vtHPEEP - ppVrec
        let Crec = Vrec / (hPEEP - lPEEP)
        let raw = max(Crec / Cbaby, 0)

        answer = String(format: "%.2f", raw)

        // Interpretation logic with multiple conditions
        if raw < 0.2 {
            interpretation = "Very Low"
            interpretationColor = .red
        } else if raw > 0.8 {
            interpretation = "Very High"
            interpretationColor = .green
        } else {
            interpretation = "Moderate"
            interpretationColor = .orange
        }

    } else {
        answer = "Invalid input"
        interpretation = ""
        interpretationColor = .gray
    }
} label: {
    Text("Calculate")
        .fontWeight(.bold)
        .frame(width: 200.0, height: 50)
        .background(Color.blue)
        .cornerRadius(10)
        .foregroundColor(.white)
        .font(.system(size: 20))
        .padding()
}

// Display result
Text("RI = \(answer)")
    .font(.system(size: 20))
    .fontWeight(.bold)

// Display interpretation with dynamic color
Text(interpretation)
    .font(.system(size: 18))
    .foregroundColor(interpretationColor)

Explanation:


1. More than two conditions:

• If raw < 0.2, it's labeled "Very Low" (Red).

• If raw > 0.8, it's labeled "Very High" (Green).

• Otherwise, it's "Moderate" (Orange).


2. Dynamic text color:

• Added a new state variable: @State var interpretationColor: Color = .gray

• Used .foregroundColor(interpretationColor) to change the text color based on conditions.


Now, when the user calculates, they'll see the result with different interpretations in different colors!

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论