绑定更改后,SwiftUI主体未重新评估

时间:2020-04-02 09:28:34

标签: swift swiftui

SwiftUI魔术的坏情况对我不起作用,我在这里失去了理智。为什么文本在这里不更新其值?为什么每次increment()通话后都没有重新评估身体?

class ReadingStateVM: ObservableObject {
    @Published var value = 0

    func increment() {
        value = value + 1
        print("value \(value)")
    }
}

struct ReadingStateView: View {
    var viewModel = ReadingStateVM()

    var body: some View {
        Text("State \(viewModel.value)")
            .onTapGesture {
                self.viewModel.increment()
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您需要添加@ObservedObject属性包装器,以便在视图模型发生更改时,视图也将更新。

@ObservedObject var viewModel = ReadingStateVM()