SwiftUI EnvironmentObject and Alert Failure

I have a default SwiftUI project for iOS. I want to run that on Apple Silicon macOS.

Here is my ContentView

import SwiftUI

struct ContentView: View {

    @StateObject var stateObj = StateObj()
    @State var showTest = false

    var body: some View {

        Button(action: {
            showTest = true
        })
        {
            Text("Test Button")
        }
        .sheet(isPresented: $showTest) {
            FailingView()
        }
        .environmentObject(stateObj)
    }
}

struct FailingView: View {
    @EnvironmentObject var stateObj: StateObj
    @State private var showAlert = false

    var body: some View {
        VStack(content: {
            Toggle(isOn: $stateObj.toggleState) {
                Text("Test")
            }
        })
        .alert(isPresented: $showAlert, content: {
            Alert(title: Text("Failure reason"))
        })
    }
}

class StateObj: ObservableObject {
    @Published var toggleState = false
}

Now I run it by selecting My Mac (Designed for iPad) and do the following

Click Test Button.

App fails with Fatal error: No ObservableObject of type StateObj found.

After removin alert method the app works as expected.

Alert method has some strange side effect that causes the app to fail on Mac.

Any ideas?

Did you try

.sheet(isPresented: $showTest) {
            FailingView().environmentObject(stateObj)
 }

I think what this is (calling back to my UIKit days). If you tried to present a UIAlertController on iPad, you had to provide sourceRect and/or sourceView so that the alert could render an arrow at a button or some UI source.

I'm getting this same error described, but dont' see a way to set those equivalents. I could be wrong though. This could be some other issue.

Actually my post above is incorrect. I can present the alert on iPhone and iPad simulators, but not on "designed for iPhone" or "designed for iPad".

SwiftUI EnvironmentObject and Alert Failure
 
 
Q