Updating worth of an Observable view mannequin inside it would not replicate the up to date worth on TextField within the view
I’m making a easy signup stream utilizing SwiftUI and I’m exhausted already. I’m unable to realize anticipated outcomes from Statement @Observable
implementing MVVM structure to work with TextField
. I’ve a ParentView
that holds a number of youngster views like- NameView
, PhoneView
, EmailView
. ParentView
holds its ViewModel
which is injected in it is youngster views. “Youngster views haven’t got their very own View Fashions”
What I anticipate:
I’m making an attempt to have regex validations for respective TextFields
stopping enter of sure characters. I feel all of the logic ought to be held in ViewModel
so by implementing the brand new Statement framework, I’m able to obtain many issues (useful) however not in relation to instantaneous two means communication between view and viewmodel utilizing that very same property particularly in case of TextField.
What’s taking place:
After I sort something within the TextField, the view mannequin property willSet/didSet closure invokes and I can carry out the operation. After I known as the validation perform from this closure, on console I get the proper worth however it would not replicate on the TextField. Nonetheless, if I add a sure delay of 0.01 seconds for instance, it updates the UI however nonetheless that deletion of character is typically seen and that is an indication of dangerous UX.
Youngster View
struct NameView: View {
@State var viewModel: ParentView.ViewModel
@FocusState var focusedField: ViewsTextField?
var physique: some View {
VStack {
TextField("", textual content: $viewModel.identify, immediate: Textual content("Full Title"))
.foregroundColor(Shade.black)
.targeted($focusedField, equals: .identify)
}
}
}
View Mannequin
extension ParentView {
@MainActor
@Observable
last class ViewModel: BaseViewModel {
var focusedField: ViewsTextField?
var identify = "" {
didSet {
print("Title: (identify)")
validateNameTextField(newValue: identify)
}
}
func validateNameTextField(newValue: String) {
let allowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
let filtered = newValue.filter { allowedCharacters.comprises($0) }
if filtered != newValue {
self.identify = filtered // This does not work but when I add a minimal delay of even 0.1 seconds enclosing in important queue then it really works however this ruins the person expertise because the deletion of character is seen on UI
}
}
}
enum ViewsTextField: Hashable {
case identify, cellphone, electronic mail
}
}
Is that this the anticipated behaviour or I’m not supposed to make use of Observable like this? I wish to perceive the proper method to my drawback.