Skip to content

Example Show Alert In SwiftUI instead build and show in every view.

License

Notifications You must be signed in to change notification settings

iletai/SingleAlertSwiftUI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Important

SwiftUI has issues in the case in a View has existed multi alert

This example suggests the way to init alert on root view instead of creating multi alert on each View

Scaleable in case iOS 18, we also moving it to Dependency Injection to control same with DDD

@main
struct AlertApp: App {
    @StateObject var alertController = AlertAppState()
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onShowAlert(with: $alertController.alert)
        }
        .environmentObject(alertController)
    }
}

extension View {
    fileprivate func onShowAlert(with alert: Binding<AlertObject?>) -> some View {
        modifier(SingleAlertViewModifier(alert: alert))
    }
}
struct ContentView: View {
    @EnvironmentObject var alertAppState: AlertAppState

    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            Text("Hello, world!")
            Button {
                alertAppState.setShowAlert(
                    AlertObject(
                        title: "Example",
                        buttonTitle: "OK",
                        buttonCancelTitle: "Cancel",
                        message: "Example",
                        action: {
                            print("OKK")
                        },
                        actionCancel: {
                            print("cancel")
                        }
                    )
                )
            } label: {
                Text("Test")
            }

        }
        .padding()
    }
}

About

Example Show Alert In SwiftUI instead build and show in every view.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages