NumberFormatter
does not function as expected under Xcode 13 betas or macOS 12 betas (currently up to beta 5 for both).
I've logged feedback to Apple FB9423179.
I'm writing a SwiftUI universal app with macOS and iOS targets using Core Data and NSPersistentCloudKitContainer
.
A Core Data Entity
is an Observed Object
in the code for a detail View
. e.g.
@ObservedObject var account: Account
where Account
is the class.
NumberFormatter
currently does not function in a TextField
on macOS 12, so as a workaround I am currently using with great success:
TextField("Sort Order",
text: Binding(
get: { String(account.sortOrder) },
set: { account.sortOrder = Int64($0.filter{"0123456789".contains($0)})! }
)
)
where sortOrder
an entity attribute of type Optional<Int64>
.
This works well for number entry and in my humble opinion is elegant in that it is immediately obvious what the TextField
is expected to do to get the information it displays and set the information provided by the user.
The only issue is that when the user makes a mistake entering a number, then backspaces or deletes the number such that the current value of the textfield is nil
, then the application crashes because of the force unwrap in the setter.
How can I make this accept a temporary value of nil?
I have tried a number of workarounds, including the use of temporary property contained in a @State
wrapper and loading and saving this temporary value using the .onAppear
and .onDisappear
modifiers, but that doesn't seem very SwiftUI to me and the downside is that the app no longer updates its UI dynamically.