使用@Observable时遇到问题。我正在用它来格式化信用卡的文本字段。我使用要点中上传的冗长代码创建了文本字段格式化程序和自定义文本字段:https://gist.github.com/amrit42087/98750b2e22b299368b07ed6e78d530a8
以下代码用于创建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))
}
}
问题是,如果我在onAppear()中使用以下这一行self.personVM.addPerson(),格式化程序将无法正常工作。注释掉此行可消除此问题。我只需要了解此问题背后的原因。任何帮助将不胜感激。
最佳答案
尝试使CreditCardTextfield
相等,以使其在personVM更新时不会重新创建。
struct CreditCardTextfield: View, Equatable {
static func == (lhs: CreditCardTextfield, rhs: CreditCardTextfield) -> Bool {
true
}
// ... other code here
并在使用地点
VStack {
CreditCardTextfield().equatable()
.offset(y: 100)
Spacer()
}