Untitled
unknown
plain_text
2 years ago
4.5 kB
6
Indexable
import SwiftUI enum Operation { case none, addition, subtraction, multiplication, division } struct ContentView: View { @State private var input: String = "" @State private var result: Double = 0 @State private var currentOperation: Operation = .none var formattedResult: String { let formatter = NumberFormatter() formatter.maximumFractionDigits = result.truncatingRemainder(dividingBy: 1) == 0 ? 0 : 2 return formatter.string(from: NSNumber(value: result)) ?? "" } var body: some View { VStack { Text("Calculator") .font(.title) .padding() TextField("Enter a number", text: $input) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() HStack { Button(action: { appendInput("7") }, label: { Text("7") .font(.title) .padding() .background(Color.gray) .foregroundColor(.white) .cornerRadius(10) }) Button(action: { appendInput("8") }, label: { Text("8") .font(.title) .padding() .background(Color.gray) .foregroundColor(.white) .cornerRadius(10) }) Button(action: { appendInput("9") }, label: { Text("9") .font(.title) .padding() .background(Color.gray) .foregroundColor(.white) .cornerRadius(10) }) Button(action: { performOperation(.division) }, label: { Text("/") .font(.title) .padding() .background(Color.orange) .foregroundColor(.white) .cornerRadius(10) }) } .padding() // Restliche Button-Gruppen hier... Button(action: { clearInput() }, label: { Text("Clear") .font(.title) .padding() .background(Color.red) .foregroundColor(.white) .cornerRadius(10) }) .padding() Text("Result: \(formattedResult)") .font(.title) .padding() } .padding() } func appendInput(_ number: String) { input += number } func performOperation(_ operation: Operation) { if let number = Double(input) { switch currentOperation { case .none: result = number case .addition: result += number case .subtraction: result -= number case .multiplication: result *= number case .division: result /= number } } else { result = 0 } currentOperation = operation // Das Textfeld wird nicht zurückgesetzt, wenn ein Operator gedrückt wird } func calculateResult() { if let number = Double(input) { switch currentOperation { case .none: result = number case .addition: result += number case .subtraction: result -= number case .multiplication: result *= number case .division: result /= number } } else { result = 0 } currentOperation = .none input = "" // Das Textfeld wird zurückgesetzt, nachdem das Ergebnis berechnet wurde } func clearInput() { input = "" result = 0 currentOperation = .none } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
Editor is loading...