致命错误:未找到ButtonState类型的ObservableObject

时间:2020-10-12 10:07:29

标签: ios swift swiftui

我在我的SwiftUI应用程序的应用程序中设置了许多环境变量,但子视图无法找到其中的一个,我也无法锻炼为什么!?!

import SwiftUI

@main
struct MentalMathSwiftUIApp: App {
    @ObservedObject var buttonState = ButtonState()
    
    var body: some Scene {
        WindowGroup {
            MainView()
                .environmentObject(buttonState)
        }
    }
}

ButtonState

class ButtonState: ObservableObject{
    
    enum ButtonState: String {
        case STOPPED
        case ACTIVE
        case PAUSED
    }
    
    @Published var currentButtonState: ButtonState = .STOPPED

MainView

struct MainView: View {
    @EnvironmentObject var buttonState: ButtonState
    
    init(){
        var t = buttonState.currentButtonState  <- **Fatal error: No ObservableObject of type ButtonState found. A View.environmentObject(_:) for ButtonState may be missing as an ancestor of this view.**
    }
    
    var body: some View {
        
        VStack {
            Text("Mental Maths!")
                .font(.largeTitle)
                .fontWeight(.heavy)
            
            ContainerView()
            MainButtonView()
        }
    }
}

您是否最好忽略init()的{​​{1}}中的毫无意义的逻辑,但是为什么我现在不能从环境变量中提取buttonState?

1 个答案:

答案 0 :(得分:2)

在调用.environmentObject以注入@EnvironmentObject之前执行初始化程序。这就是为什么尝试从init访问所述环境对象会导致致命错误的原因。

您应该在初始化中注入对象,而不是将其设置为@EnvironmentObject以避免运行时崩溃。

struct MainView: View {
    @ObservedObject var buttonState: ButtonState
    
    var body: some View {
        
        VStack {
            Text("Mental Maths!")
                .font(.largeTitle)
                .fontWeight(.heavy)
            
            ContainerView()
            MainButtonView()
        }
    }
}

@main
struct MentalMathSwiftUIApp: App {
    @ObservedObject var buttonState = ButtonState()
    
    var body: some Scene {
        WindowGroup {
            MainView(buttonState: buttonState)
        }
    }
}