为什么我发布的var没有被我的视图更新?



我正在做一个个人项目来研究SwiftUI。一切都很顺利,然后我注意到我的应用程序有一个bug。

我有下面的简单视图,它保存了一个描述,一个值和我的ViewModel上的一些标签。我有一个问题与$viewModel.value. 该变量没有被视图中的值填充。

我假设我的@Published var value: Double?从我的ViewModel应该更新,每当用户键入一些值。问题是,它不能在任何iPhone 11及以上版本上更新,但它在iPhone 8上运行得很好。

public struct AddBillView: View {

@ObservedObject private var viewModel: AddBillViewModel

@Environment(.presentationMode) var presentationMode

public let onExpenseCreated: ((_ expense: Expense)->Void)

public var body: some View {
Text("Add Expense")
VStack {
TextField("Descrição", text: $viewModel.name)
HStack {
Text("Valor (NumberFormatter.currency.currencySymbol)")
CurrencyTextField("Value", value: $viewModel.value)
.multilineTextAlignment(TextAlignment.leading)
}

HStack {
Text("Tags")
TextField("car pets home",
text: $viewModel.tags)
}

Picker("Type", selection: $viewModel.type) {
Text("Paid").tag("Paid")
Text("Unpaid").tag("Unpaid")
Text("Credit").tag("Credit")
}
}.navigationTitle("+ Expense")

Button("Adicionar") {
if !viewModel.hasExpense() {
return
}
onExpenseCreated(viewModel.expense())
self.presentationMode.wrappedValue.dismiss()
}
}

public init(viewModel outViewModel: AddBillViewModel,
onExpenseCreated: @escaping ((_ expense: Expense)->Void)) {
self.viewModel = outViewModel
self.onExpenseCreated = onExpenseCreated
}
}
我有一个ViewModel:
public class AddBillViewModel: ObservableObject {
@Published var name: String = ""
@Published var type: String = "Paid"
@Published var tags: String = ""
@Published var value: Double?


init(expense: Expense?=nil) {
self.name = expense?.name ?? ""
self.type = expense?.type.rawValue ?? "Paid"
self.tags = expense?.tags?.map { String($0.name) }.joined(separator: " ") ?? ""
self.value = expense?.value
}

func hasExpense() -> Bool {
if self.name.isEmpty ||
self.value == nil ||
self.value?.isZero == true {
return false
}
return true
}

func expense() -> Expense {
let tags = self.tags.split(separator: " ").map { Tag(name: String($0)) }
return Expense(name: self.name, value: self.value ?? 0.0 ,
type: ExpenseType(rawValue: self.type)!,
id: UUID().uuidString,
tags: tags)
}
}

然后我使用我的视图:


AddBillView(viewModel: AddBillViewModel()) { expense in
viewModel.add(expense: expense)
viewModel.state = .idle
}

我已经谷歌了,花了几个小时寻找答案,没有运气。有人有什么想法吗?

下面是CurrencyTextField的代码。我使用这个组件:https://github.com/youjinp/SwiftUIKit/blob/master/Sources/SwiftUIKit/views/CurrencyTextField.swift但是该组件在iPhone 8模拟器上工作得很好,并且在我的视图中有一个@State属性。它不工作,只与我的ViewModel

我明白了!问题是我的AddBillViewModel是一个ObservableObject我用@Published标记每个属性. 这会导致某种双重可观察对象。

删除@Published它又开始工作了。

相关内容

  • 没有找到相关文章

最新更新