I am stuck in a problem while using @Observable. I am using it to format a textfield for credit card. I created a textfield formatter and a custom textfield using a lengthy code that I have uploaded in a gist: https://gist.github.com/amrit42087/98750b2e22b299368b07ed6e78d530a8
The below code is using for creating the UI:
import SwiftUI
struct Person: Identifiable {
var id = UUID()
var name: String
var age: Int
}
struct View1: View {
@ObservedObject var personVM = PersonViewModel()
var body: some View {
NavigationView {
HStack {
Spacer()
VStack {
CreditCardTextfield()
.offset(y: 100)
Spacer()
}
Spacer()
}
.onAppear {
self.personVM.addPerson()
}
}
}
}
struct CreditCardTextfield: View {
@ObservedObject var cardFormatter = TextFieldFormatter(limit: 19, type: .cardNumber)
@State var isFirstResponder = false
var body: some View {
CustomTextField(text: $cardFormatter.text, isFirstResponder: $isFirstResponder, placeholder: "XXXX XXXX XXXX XXXX", font: .monospacedSystemFont(ofSize: 25, weight: .bold), keyboardType: .numberPad)
.frame(height: 40)
}
}
class PersonViewModel: ObservableObject {
@Published var people: [Person] = []
func addPerson() {
people.append(Person(name: "Test", age: (0...30).randomElement() ?? 0))
}
}
The problem is that formatter does not work if I use this line self.personVM.addPerson() in onAppear(). Commenting out this line eradicates the problem. I just need to understand the reason behind this issue. Any help would be more than appreciated.