I'm trying to store a user's text field entry as a number so it's easier to work with in formulas. I thought I was being slick by storing it as a string, but now using the input in mathematical formulas is becoming a real pain in the neck. It should be noted that these field entries are being stored in CoreData currently as a string entity.
Here's an MRE of one of my fields:
import SwiftUI
struct EntryMRE: View {
@Environment(\.managedObjectContext) private var viewContext
@State private var showingResults: Int? = 1
@FocusState private var isTextFieldFocused: Bool
@State var isDone = false
@State var isSaving = false //used to periodically save data
@State var saveInterval: Int = 5 //after how many seconds the data is automatically saved
//DataPoints Chemistry
@State var potassium = ""
var body: some View {
List {
Section(header: Text(" Chemistry")) {
Group {
HStack {
Text("K")
+ Text("+")
.font(.system(size: 15.0))
.baselineOffset(4.0)
Spacer()
TextField("mEq/L", text: $potassium)
.focused($isTextFieldFocused)
.foregroundColor(Color(UIColor.systemBlue))
.modifier(TextFieldClearButton(text: $potassium))
.multilineTextAlignment(.trailing)
.keyboardType(.decimalPad)
if let numberValue = Double(potassium) { // Cast String to Double
if (3.5...5.5) ~= numberValue {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(Color(UIColor.systemGreen))
}
else {
Image(systemName: "exclamationmark.circle.fill")
.foregroundColor(Color(UIColor.systemRed))
}
}
}
}
}
}
}
}
While not specifically using the $potassium value, here is what I'm currently having to do for formulas:
import SwiftUI
struct ResultView: View {
@Binding var isDone: Bool
var EV: EntryView
let decimalPlaces: Int = 2
var body: some View {
List {
Section(header: Text("Formula")) {
HStack {
Text("Corrected CO2")
Spacer()
Text("\(1.5 * (Double(EV.hCo3) ?? 0) + 8, specifier: "%.\(decimalPlaces)f")")
}