SwiftUI-从ObservableObject触发模态表?

时间:2020-10-01 06:10:38

标签: view swiftui observableobject

我已经创建了一个随机数生成器,如果出现数字3,该生成器应该显示一个新的工作表。

逻辑位于单独的类中,但是当我在ContentView上使用.sheet.fullScreenCover时,它将无法正常工作。

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

下面的最小可重复示例:

    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
        }       
    }  
}

1 个答案:

答案 0 :(得分:1)

@State旨在显示在视图中,在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测试