如何获取在另一个视图中更新变量的结构函数,并在更改后刷新该视图?

时间:2020-08-26 16:56:18

标签: swift swiftui

import SwiftUI
import Combine

struct ContentView: View {
    
    var subtract = MinusToObject()
    
    
    var body: some View {
        VStack{
            
            Text("The number is \(MyObservedObject.shared.theObservedObjectToPass)")
            Text("Minus")
                .onTapGesture {
                    subtract.subtractIt()
                }
            
            NavigationView {
                NavigationLink(destination: AnotherView()) {
                    Text("Push")
                }.navigationBarTitle(Text("Master"))
            }

            
        }
    }
}

class MyObservedObject: ObservableObject {
    static let shared = MyObservedObject()
    private init() { }
    
    @Published var theObservedObjectToPass = 6
}

struct MinusToObject {
    func subtractIt() {
        MyObservedObject.shared.theObservedObjectToPass -= 1
    }
}

当我点击Minus调用我的subtract实例的函数时,我知道该值会发生变化,因为如果我转到另一个视图,则可以看到新的值,但是当前视图不会。 t更新。

我认为我必须在var subtract = MinusToObject()周围放一个属性包装器(我已经盲目地尝试了几个),我觉得我应该将$放到某个地方进行双向绑定,但是我无法确定在哪里。

1 个答案:

答案 0 :(得分:1)

ERROR TypeError: this is undefined 是多余的。这是方法(如果需要,可以共享MyObservedObject)...

ERROR TypeError: this is undefined
    successDeleteCarAndUpdateView profile.component.ts:795
    deleteCar car.service.ts:62
    RxJS 11
        __tryOrUnsub
        next
        _next
        next
        _next
        next
        _next
        next
        notifyNext
        _next
        next
    Angular 8
        onLoad
        invokeTask
        onInvokeTask
        invokeTask
        runTask
        invokeTask
        invokeTask
        globalZoneAwareCallback