Showing an alert, which disappears after a second by itself

I would like to show a quick message to the user, which disappears by itself after a second or two. In Android you got so-called “MessageToasts” (Android Docu) and “SnackBars”, which serve the described purpose. In Web I have seen such elements too as “FlashMessages”.
Is there a similar element in SwiftUI or does one have to use a third-party library for it?

You could create a View which slides in and slides out or fades in and then fades out. There are plenty of ways to do it as a custom View.

For example, this code slides in MessageView from the right and after 2 seconds it slides back out again:

struct ParentMessageView: View {
    @State private var isShowingMessageView = false

    var body: some View {

        ZStack {
            VStack(spacing: 20) {
                Image(systemName: "globe")
                    .imageScale(.large)
                    .foregroundColor(.accentColor)
                Text("Hello, world!")
                Button("Show Message View") {
                    withAnimation {
                        displayMessage()
                    }
                }
                Spacer()
            }
            .padding(.top, 100)
            
            MessageView(isShowingMessageView: $isShowingMessageView)
        }
        .ignoresSafeArea()
    }

    func displayMessage() {
        // Slide the message in
        isShowingMessageView = true

        // After 2 seconds, side the message out
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            withAnimation {
                isShowingMessageView = false
            }
        }
    }
}

struct ParentMessageView_Previews: PreviewProvider {
    static var previews: some View {
        ParentMessageView()
    }
}

MessageView

struct MessageView: View {
    @Binding var isShowingMessageView: Bool

    var body: some View {
        GeometryReader { gr in
            ZStack {
                RoundedRectangle(cornerRadius: 20)
                    .fill(Color.offWhite)
                    .frame(maxWidth: gr.size.width - 50, maxHeight: 100)
                    .shadow(color: Color.black.opacity(0.6), radius: 8, x: 5, y: 5)
                Text("Slide in Message")
                    .font(.largeTitle)
            }
            .position(x: isShowingMessageView ? gr.size.width / 2 : gr.size.width + gr.size.width - 50 / 2, y: gr.size.height / 2)

        }
    }
}

struct PopInView_Previews: PreviewProvider {
    static var previews: some View {
        MessageView(isShowingMessageView: .constant(true))
    }
}

Depending on what kind of message you are going to show to the user you need to give them time to read it before sliding it out of the way. The longer the message the more time you need to leave it on the screen for.

Anyway, I hope this gives you an idea.

2 Likes

Coool … :slight_smile: Thanks a lot!