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.
could not understand how to search for your feedback on the apple site. What is the problem with NumberFormatter in a textField? It seems to work for me.
Probably shouldn't have included a link for the FB. But I figured out why
NumberFormatter
is not working for me... In my Core Data object graph and using my example above, the entitysortOrder
is an Integer 64 type with "Use Scalar Type" checked. So when CodeGen creates an automatically generated property for myAccount
class, it does so with an entity attribute of type Int64 (or perhaps more correctly int64_t) instead of the (non-scalar)NSNumber
. So from this I can only assume thatNumberFormatter
requires a non-scalar typeNSNumber
. I have a few reasons why I use scalar types but I expect that this will prompt me to do two things - update my feedback AND consider whether I transition to using non-scalar types in my SwiftUI code.