在 SwiftUI 中从外部 class 打开 .sheet()

Open a .sheet() from an outside class in SwiftUI

我尝试了一些使用 ObservableObject 和 @Published 的变体,试图通过外部 class 从更新中打开我的 ContentView 中的 sheet,但我无法将其打开工作。

如何使用 Observable/Observed 对象实现此目的?

import SwiftUI

class SheetObservable: ObservableObject {
    @Published var isActive = false
}

struct ContentView: View {
    @ObservedObject var Sheet = SheetObservable()
    var body: some View {
        Button(action:{
            Actions().openSheet()
        }){
            Text("Open Sheet")
        }
        .sheet(isPresented: self.$Sheet.isActive) {
            EmptyView()
        }
    }
}

class Actions {
    @ObservedObject var Sheet = SheetObservable()
    public func openSheet() {
        print("openSheet fired()")
        self.Sheet.isActive = true
    }
}

需要使用ObjservableObject的相同实例,所以这里是固定代码

struct ContentView: View {
    @ObservedObject var Sheet = SheetObservable()
    var body: some View {
        Button(action:{
            Actions(sheet: self.Sheet).openSheet()
        }){
            Text("Open Sheet")
        }
        .sheet(isPresented: self.$Sheet.isActive) {
            EmptyView()
        }
    }
}

class Actions {
    @ObservedObject var Sheet: SheetObservable

    init(sheet: SheetObservable) {
        self.Sheet = sheet
    }

    public func openSheet() {
        print("openSheet fired()")
        self.Sheet.isActive = true
    }
}

测试 Xcode 11.4 / iOS 13.4