I am using a TextField
to update a numeric value in my app model. The page editing the values is triggered from a NavigationView
. Everything works fine when I use a default keyboard, ie:
TextField("Enter a number", value: $userData.chosenNumber, formatter: NumberFormatter())
.keyboardType(.default)
will update the value of userData.chosenNumber
when hitting the Return key and this change is reflected on the main navigation screen (userData
is an EnvironmentObject
).
However, the same code using .keyboardType(.numberPad)
instead won't show a Return key, and userData.chosenNumber
won't be updated when navigating back to the main view. This happens both in the simulator and live on device (but things work as expected using SwiftUI live preview, or in the simulator when hitting the physical keyboard Return key).
Is there a way to get the new value picked up please without having to use a default keyboard?
--Edit--
Based on pawello2222's suggestion in the comments, I tried the solution in this other SO's question but that didn't fully work in my case.
What the other question suggests: introducing a Binding<String>
(via a computed property) that acts as intermediate between the value I want to modify and the string displayed in the UI.
- This works to modify the value inside my view.
- However the runtime fails to detect that the
EnvironmentObject
injected by the parent view is modified, so after leaving the view the app UI is not refreshed and the other views do not get updated.
(For some context, my app computes a diver's bottom time based on an air tank site and the diver's air consumption. The detail view is used to edit the diver's air consumption value while another view displays the resulting bottom time. So in my case the diver's consumption gets updated, but the bottom time doesn't receive an update, unlike what happens with a standard keyboard.)