SwiftUI - 从 ObservableObject 触发模式 Sheet?

SwiftUI - Trigger a Modal Sheet from an ObservableObject?

我创建了一个随机数生成器,如果出现数字 3,它应该会显示一个新的 sheet。

逻辑在单​​独的 class 中,但是当我在 ContentView 上使用 .sheet.fullScreenCover 时它不起作用。

是否可以从 Xcode12 / iOS 14 SwiftUI 中的 ObservableObject 触发模态 sheet?

下面的最小可重现示例:

    import SwiftUI
    
    struct ContentView: View {
        
        @StateObject var mathLogic = MathLogic()
        
        var body: some View {
            
            VStack{
                
            Text(String(mathLogic.newNumber))
                .padding(.bottom, 40)
        
            Text("Tap for a number")
                             .onTapGesture{
                                 mathLogic.generateRandomNumber()
                             }
      }
        .fullScreenCover(isPresented: mathLogic.$isLucky3, content: NewModalView.init)
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct NewModalView: View {
    
    var body: some View {
        Text("You hit lucky number 3!")
    }
}

class MathLogic: ObservableObject {
    
    @Published var newNumber = 0
    
    @State var isLucky3 = false
    
    func generateRandomNumber() {
        
        newNumber = Int.random(in: 1..<5)
        
        guard self.newNumber != 3 else {
            // trigger modal
            self.isLucky3.toggle()        
            return
        }       
    }  
}

中的@State是为了在View中,在ObservableObject中我们使用@Published,所以应该是

class MathLogic: ObservableObject {
    
    @Published var newNumber = 0
    
    @Published var isLucky3 = false    // << here !!

// .. other code

并通过 ObservedObject 绑定它,因为 .$isLucky3 给发布者

    // ... other code
  }
  .fullScreenCover(isPresented: $mathLogic.isLucky3, content: NewModalView.init)

测试 Xcode 12 / iOS 14