我正在嘗試將用戶的文本欄位條目存盤為數字,以便在公式中更容易使用。我以為我把它存盤為一個字串是很狡猾的,但現在在數學公式中使用輸入正在成為一個真正的痛苦。應該注意的是,這些欄位條目當前作為字串物體存盤在 CoreData 中。
這是我的一個領域的 MRE:
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))
}
}
}
}
}
}
}
}
雖然沒有專門使用 $potassium 值,但這是我目前必須為公式做的事情:
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")")
}
uj5u.com熱心網友回復:
如果你希望你@State var potassium是型別Double,你可以為你的TextField.
@State var potassium = 0.0
TextField("mEq/L", value: $potassium, format: .number)
當然,您需要將CoreData模型更改為型別Double,但我認為這首先應該是 a Double。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/465190.html
