Create Apple-like alerts & toasts using SwiftUI

Overview

AlertToast-SwiftUI Tweet

Present Apple-like alert & toast in SwiftUI

๐ŸŒ„ Example

๐Ÿ”ญ Overview

Currently in SwiftUI, the only way to inform the user about some process that finished for example, is by using Alert. Sometimes, you just want to pop a message that tells the user that something completed, or his message was sent. Apple doesn't provide any other method rather than using Alert even though Apple using all kinds of different pop-ups. The results are poor UX where the user would need to tap "OK/Dismiss" for every little information that he should be notified about.

Alert Toast is an open-source library in Github to use with SwiftUI. It allows you to present popups that don't need any user action to dismiss or to validate. Some great usage examples: Message Sent, Poor Network Connection, Profile Updated, Logged In/Out, Favorited, Loading and so on...

         

  • Built with pure SwiftUI.
  • 3 Display modes: Alert (pop at the center), HUD (drop from the top) and Banner (pop/slide from the bottom).
  • Complete, Error SystemImage, Image, Loading, and Regular (Only Text).
  • Supports Light & Dark Mode.
  • Works with any kind of view builder.
  • Localization support.
  • Font & Background customization.

If you like the project, don't forget to put star ๐ŸŒŸ.

      

Navigation

๐Ÿ’ป Installation

Cocoapods

AlertToast Cocapods Website

CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate AlertToast into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'AlertToast'

Swift Package Manager

The Swift Package Manager is a tool for managing the distribution of Swift code. Itโ€™s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.

To integrate AlertToast into your Xcode project using Xcode 12, specify it in File > Swift Packages > Add Package Dependency...:

https://github.com/elai950/AlertToast.git, :branch="master"

Manually

If you prefer not to use any of dependency managers, you can integrate AlertToast into your project manually. Put Sources/AlertToast folder in your Xcode project. Make sure to enable Copy items if needed and Create groups.

๐Ÿงณ Requirements

  • iOS 13.0+ | macOS 11+
  • Xcode 12.0+ | Swift 5+

๐Ÿ›  Usage

First, add import AlertToast on every swift file you would like to use AlertToast.

Then, use the .toast view modifier:

Parameters:

  • isPresenting: (MUST) assign a Binding<Bool> to show or dismiss alert.
  • duration: default is 2, set 0 to disable auto dismiss.
  • tapToDismiss: default is true, set false to disable.
  • alert: (MUST) expects AlertToast.

Usage example with regular alert

import AlertToast
import SwiftUI

struct ContentView: View{

    @State private var showToast = false

    var body: some View{
        VStack{

            Button("Show Toast"){
                 showAlert.toggle()
            }
        }
        .toast(isPresenting: $showToast){

            // `.alert` is the default displayMode
            AlertToast(type: .regular, title: "Message Sent!")
            
            //Choose .hud to toast alert from the top of the screen
            //AlertToast(displayMode: .hud, type: .regular, title: "Message Sent!")
            
            //Choose .banner to slide/pop alert from the bottom of the screen
            //AlertToast(displayMode: .banner(.slide), type: .regular, title: "Message Sent!")
        }
    }
}

Complete Modifier Example

.toast(isPresenting: $showAlert, duration: 2, tapToDismiss: true, alert: {
   //AlertToast goes here
}, onTap: {
   //onTap would call either if `tapToDismis` is true/false
   //If tapToDismiss is true, onTap would call and then dismis the alert
}, completion: {
   //Completion block after dismiss
})

Alert Toast Parameters

AlertToast(displayMode: DisplayMode,
           type: AlertType,
           title: Optional(String),
           subTitle: Optional(String),
           custom: Optional(AlertCustom))
           
//This is the available customizations parameters:
AlertCustom(backgroundColor: Color?,
            titleColor: Color?,
            subTitleColor: Color?,
            titleFont: Font?,
            subTitleFont: Font?)

Available Alert Types:

  • Regular: text only (Title and Subtitle).
  • Complete: animated checkmark.
  • Error: animated xmark.
  • System Image: name image from SFSymbols.
  • Image: name image from Assets.
  • Loading: Activity Indicator (Spinner).

Alert dialog view modifier (with default settings):

.toast(isPresenting: Binding<Bool>, duration: Double = 2, tapToDismiss: true, alert: () -> AlertToast , onTap: () -> (), completion: () -> () )

Simple Text Alert:

AlertToast(type: .regular, title: Optional(String), subTitle: Optional(String))

Complete/Error Alert:

AlertToast(type: .complete(Color)/.error(Color), title: Optional(String), subTitle: Optional(String))

System Image Alert:

AlertToast(type: .systemImage(String, Color), title: Optional(String), subTitle: Optional(String))

Image Alert:

AlertToast(type: .image(String), title: Optional(String), subTitle: Optional(String))

Loading Alert:

//When using loading, duration won't auto dismiss and tapToDismiss is set to false
AlertToast(type: .loading, title: Optional(String), subTitle: Optional(String))

You can add many .toast on a single view.

๐Ÿ“– Article

I wrote an article that contains more usage exmaples.

Medium - How to toast an alert in SwiftUI

๐Ÿ‘จโ€๐Ÿ’ป Contributors

All issue reports, feature requests, pull requests and GitHub stars are welcomed and much appreciated.

โœ๏ธ Author

Elai Zuberman

๐Ÿ“ƒ License

AlertToast is available under the MIT license. See the LICENSE file for more info.


Comments
  • Wrong position of toast while displaying in sheet

    Wrong position of toast while displaying in sheet

    Describe the bug Toast will show in wrong position with hud display mode when using it in sheet. This bug appears only in iOS

    To Reproduce Steps to reproduce the behavior:

    1. Define a view as sheet
    2. Add toast to it with hud display mode
    3. Call the toast to show

    Expected behavior The Y Position of Toast should be much more below or even below the NavigationView (if is defined)

    Screenshots IMG_0361

    Smartphone:

    • Device: iPhone 12
    • OS: iOS 14.4

    Sample code:

    import SwiftUI
    import AlertToast
    
    struct ContentView: View {
        
        @State private var showingDetail = false
        
        var body: some View {
            Button("Show Detail") {
                showingDetail.toggle()
            }
            .sheet(isPresented: $showingDetail) {
                NextView()
            }
        }
    }
    
    struct NextView: View {
        
        @State var showToast = false
        
        var body: some View {
            ScrollView {
                Button("Show Detail") {
                    showToast.toggle()
                }
                .padding()
            }.toast(isPresenting: $showToast, duration: 3, tapToDismiss: true, alert: {
                AlertToast(
                    displayMode: .hud,
                    type: .systemImage("checkmark.circle.fill", .green),
                    title: "Test",
                    subTitle: "Some message")
                
            })
        }
    }
    
    bug 
    opened by Rminsh 6
  • Alert can never be dismissed

    Alert can never be dismissed

    This is a really cool framework but I am having problem dismissing the alert if I set duration greater than 2.0. Default setting works as expected.

    This works perfectly (view diasappears after 2 seconds):

    .toast(isPresenting: RM.$pendingNotifications) {
                    AlertToast(displayMode: .hud, type: .systemImage("exclamationmark.triangle.fill", Color.orange), title: "alert alert alert")
                }
    

    The code below does not work. With any duration above 2.0 the view appears and never disappears. It stays on top of the screen. Tap to dismiss also does not work. I also cannot influence anything with tapToDismiss:

    .toast(isPresenting: RM.$pendingNotifications, duration: 3.0) {
                    AlertToast(displayMode: .hud, type: .systemImage("exclamationmark.triangle.fill", Color.orange), title: "alert alert alert")
                }
    

    RM is an observable object exposed to the environment and pendingNotifications is @Published variable.

    opened by A320Peter 5
  • No such module AlertToast

    No such module AlertToast

    I try to install manually AlertToast as per instructions, but I got error "No such module AlertToast" in Xcode 12.4. Is there way to fix this?

    opened by goxyed 4
  • Dismiss does not work when using .loading alert

    Dismiss does not work when using .loading alert

    Describe the bug I expect to display loading alert. Once Published variable changes to different value then I'd expect new alert to display only 2 seconds, not infinite. Also tap to dismiss does not work in this case

    Expected behavior .toast(isPresenting: $showToast) { if viewModel.sendMessageResponse == .successfullySent { return AlertToast(type: .complete(.green), title: "Message Sent!", custom: .custom(backgroundColor: Color.customYellow)) } else if viewModel.sendMessageResponse == .errornousResponse { return AlertToast(type: .error(.red), title: "Unable to send message!", custom: .custom(backgroundColor: Color.customYellow)) } else { return AlertToast(displayMode: .alert, type: .loading, custom: .custom(backgroundColor: Color.customYellow)) }

    Steps

    1. Change showToast to true -> this displays loading alert
    2. Waiting for async call to update sendMessageResponse to .successfullySent or .errornousResponse
    3. Alert green or red is displayed infinitely and it is impossible to to tap to dismiss success/error alert.
    bug 
    opened by bzbislawski 3
  • Invalid frame dimension (negative or non-finite).

    Invalid frame dimension (negative or non-finite).

    Describe the bug Invalid frame dimension (negative or non-finite).

    Screenshots If applicable, add screenshots to help explain your problem.

    Desktop (please complete the following information):

    • OS: iOS

    Smartphone (please complete the following information):

    • Device: iPhone 11
    • OS: iOS 15 beta 6
    bug 
    opened by underthestars-zhy 3
  • Menu style wanted

    Menu style wanted

    The swiftUI default Menu style is very restrict, it is hard to custom the content style. And I find that all the open source toast don't have it. I am a product manager learning swiftUI, so is it possible to add custom view for menu like style, and click the button shows the content view. My thinking is pass the location of the clicked button and show the toast with the location in the toast? Thank you so much.

    opened by xiaoxidong 3
  • Alert Toast (.hud display mode) is displayed behind the navigation bar items

    Alert Toast (.hud display mode) is displayed behind the navigation bar items

    Describe the bug If there is a navigation bar item that has a long text, the .alert toast will be displayed behind it

    To Reproduce Steps to reproduce the behavior:

    1. Create a view with a NavigationView
    2. Add a navigation bar item with a long text to the trailing position (example: Add to favorite)
    3. Trigger an .hud AlertToast

    Expected behavior The AlertToast should be on top of the navigation bar items

    Screenshots Simulator Screen Shot - iPhone 13 - 2021-11-14 at 14 50 24

    Smartphone:

    • Device: iPhone 13
    • OS: iOS 15
    • Version: 1.3.7
    bug 
    opened by Matttx 2
  • Issue: Swift Compiler Error when adding package

    Issue: Swift Compiler Error when adding package

    Expected Behavior

    I am able to add the package and build/run my application without errors.

    Actual Behavior

    Once I add the package and try to build, I get "153 issues" which are all Swift Compiler Errors

    Screen Shot 2021-10-26 at 7 44 44 PM

    Steps to Reproduce the Problem

    1. Open XCode project and add package using Swift Package Manager
    2. Add import statement "import AlertToast"
    3. Build

    Specifications

    • SwiftUI Version: 5
    • Platform (iOS or macOS): watchOS
    good first issue 
    opened by cindychea 2
  • 'AlertToast' initializer is inaccessible due to 'internal' protection level

    'AlertToast' initializer is inaccessible due to 'internal' protection level

    Updated to version 1.3.5 and still seeing this error message in Xcode 13.

    'AlertToast' initializer is inaccessible due to 'internal' protection level

    .toast(isPresenting: $showToast){
                
                AlertToast(displayMode: .hud, type: .systemImage(toastImage!, toastImageColor!), title: toastTitle, subTitle: toastSubTitle)
                    
            }
    
    bug 
    opened by solidHeroLink 2
  • Update the animation property in SwiftUI 3 (Xcode 13)

    Update the animation property in SwiftUI 3 (Xcode 13)

    Describe the bug A clear and concise description of what the bug is.

    'animation' was deprecated in macOS 12.0: Use withAnimation or animation(_:value:) instead.

    To Reproduce Steps to reproduce the behavior:

    1. Go to '...'
    2. Click on '....'
    3. Scroll down to '....'
    4. See error

    Expected behavior A clear and concise description of what you expected to happen.

    Screenshots If applicable, add screenshots to help explain your problem.

    Desktop (please complete the following information):

    • OS: [e.g. iOS]
    • Browser [e.g. chrome, safari]
    • Version [e.g. 22]

    Smartphone (please complete the following information):

    • Device: [e.g. iPhone6]
    • OS: [e.g. iOS8.1]
    • Browser [e.g. stock browser, safari]
    • Version [e.g. 22]

    Additional context Add any other context about the problem here.

    bug 
    opened by rsyncOSX 2
  • Toast renders behind Keyboard.

    Toast renders behind Keyboard.

    Describe the bug I'm not sure if that's possible to achieve, but when showing a toast alert while a keyboard is shown the toast renders behind it.

    To Reproduce Steps to reproduce the behavior:

    1. Create a SwiftUI View
    2. Create a textfield and Button
    3. The Button should "activate" a toast alert.
    4. Now type something in the textfield and press the button when the keyboard is shown. Here you go...

    Expected behavior I'd expect the toast to render in front of the keyboard, still I'm not sure if that's possible to achieve.

    Screenshots If applicable, add screenshots to help explain your problem. image

    Desktop (please complete the following information):

    • only on iOS!

    Smartphone (please complete the following information):

    • Device: iPhone 11
    • OS: iOS 14.4.2

    Additional context Add any other context about the problem here. Still thank you for the nice library.

    bug 
    opened by toqix 2
  • Swipe to dismiss toast

    Swipe to dismiss toast

    Is your feature request related to a problem? Please describe. At the moment it is only possible to dismiss a toast by tapping on it.

    Describe the solution you'd like It would be nice if we could dismiss it by swiping (up|down) depending on where it is located on the screen.

    opened by lukepistrol 0
  • Fix: alert modifier should not modify duration to zero when alert type equals to alert

    Fix: alert modifier should not modify duration to zero when alert type equals to alert

    Signed-off-by: zangqilong [email protected]

    It's better to not set duration to zero when type equal to loading. here is the sample code to explain. I create a AlertContext to manage different alert state and use single .toast modifier to present different toast.

    enum AlertState: Equatable {
        case none
        case success(title: String)
        case failure(title: String)
        case loading
        
        var duration: TimeInterval {
            return 2
        }
        
        func alertView() -> AlertToast {
            switch self {
            case .none:
                return AlertToast(displayMode: .alert, type: .regular)
            case .success(let title):
                return AlertToast(displayMode: .alert, type: .complete(.white), title: title)
            case let .failure(title):
                return AlertToast(displayMode: .alert, type: .error(.white), title: title)
            case .loading:
                return AlertToast(displayMode: .alert, type: .loading)
            }
        }
    }
    
    final class AlertContext: ObservableObject {
        @Published var showAlert = false
        @Published var state = AlertState.none {
            didSet {
                switch state {
                case .none:
                    showAlert = false
                default:
                    showAlert = true
                }
            }
        }
    }
    
    

    and the view use this } .toast(isPresenting: $context.showAlert, duration: context.state.duration) { context.state.alertView() }

    if use the old way to set the duration = 0 when alertType == .alert, the modifier's duration will be zero forever it means when I change the context.state to success or failure, the auto dimiss will never work again.

    opened by zangqilong198812 0
  • tvOS compatibility possible?

    tvOS compatibility possible?

    Is your feature request related to a problem? Please describe. It's not really a problem but I'm just porting my iOS app to tvOS and I was surprised that this library doesn't work on tvOS. Is there any specific reason for that?

    Describe the solution you'd like To be able to use this lib on tvOS apps.

    Describe alternatives you've considered Only other solution is to not use AlertToast on tvOS and build the view in a different way.

    Additional context I just finished porting my Android app to iOS so some of the Apple stuff is still new to me. If it is obvious why this lib can't work on tvOS I'm sorry for creating this ticket.

    opened by grill2010 0
  • toast<Item>(item: Binding<Item?>, content: (Item) -> AlertToast) modifier

    toast(item: Binding, content: (Item) -> AlertToast) modifier

    iOS 15.5 removed the alert<Item>(item: Binding<Item?>, content: (Item) -> Alert) modifier which was super useful to construct an Alert based on the item wrapped by the Binding.

    the replacement alert(isPresented: Bool) variants are not as powerful.

    It would be really cool to add the item based modifier to AlertToast to enable a straight forward replacement. I can attempt to build it if there is interest and nobody else is working on it.

    opened by ekurutepe 0
Owner
Elai Zuberman
iOS Mobile Developer
Elai Zuberman
Display Apple system-like self-hiding status alerts. It is well suited for notifying user without interrupting user flow in iOS-like way.

StatusAlert is being sponsored by the following tool; please help to support us by takin a look and signing up to a free trial. Dependency managers Fe

Yehor Miroshnychenko 841 Dec 6, 2022
DropView - A SwiftUI library to display Apple Pencil and Pasteboard-like alerts on iOS.

DropView is a SwiftUI-based library to display alerts inspired by the Apple Pencil and pasteboard stock ones.

Stefano Bertagno 46 Dec 4, 2022
A ยตFramework for showing alerts like the one used when copying from pasteboard or connecting Apple pencil

Drops ?? A ยตFramework for showing alerts like the one used when copying from pasteboard or connecting Apple pencil. Features iOS 10+ Can be used in Sw

Omar Albeik 709 Dec 29, 2022
Easily create different alerts in SwiftUI

AlertWizard ????โ€โ™‚๏ธ This package lets you easily create different alerts in SwiftUI with the call of a single function. As this is my first package th

null 3 Jun 3, 2021
Toasts and popups library written with SwiftUI

Popup View Toasts and popups library written with SwiftUI We are a development agency building phenomenal apps. Usage Put all your body code into a ZS

Exyte 1.9k Jan 5, 2023
๐Ÿž Loaf is a Swifty Framework for Easy iOS Toasts

Loaf ?? Inspired by Android's Toast, Loaf is a Swifty Framework for Easy iOS Toasts Usage From any view controller, a Loaf can be presented by calling

Mat Schmid 995 Dec 28, 2022
Bursts ๐Ÿ”ฅ A Funny Framework is showing alerts, Have been Adapting Swift and SwiftUI

Bursts ?? A Funny Framework is showing alerts, Have been Adapting Swift and SwiftUI Features iOS 10+ Can be used in UIKit and SwiftUI applications Lig

Jovins 11 Apr 22, 2022
It is a highly configurable iOS library which allows easy styling with built in styles as well as extra header and footer views so that you can make extremely unique alerts and action sheets.

๏ฃฟ CFAlertViewController CFAlertViewController is a library that helps you display and customise Alerts, Action Sheets, and Notifications on iPad and i

Crowdfire Inc. 1.1k Dec 18, 2022
Advance animated alerts for iOS written in Swift

LIHAlert LIHAlert provides animated banners for iOS. Updated to Swift 3 Demo Project The LIHAlert workspace contains a demo project, also used for dev

null 37 Dec 9, 2022
๐ŸšจUse the iPhone X Notch to display alerts. ๐Ÿšจ

NotchyAlert Prerequisites Xcode 9.x Swift 4.x iPhone X Simulator/Device Demo Installation Cocoapods To install NotchyAlert using Cocoapods, add the fo

Sofiane Beors 70 Nov 20, 2022
BeautyAlert - BeautyAlert provides alerts with custom shapes, colors, buttons

BeautyAlert helps you can easily design by determining the color, shape, and sha

chacha 17 Sep 8, 2022
An iOS library for SwiftUI to create draggable sheet experiences similar to iOS applications like Maps and Stocks.

An iOS library for SwiftUI to create draggable sheet experiences similar to iOS applications like Maps and Stocks.

Wouter 63 Jan 5, 2023
This is an iOS control for selecting a date using UIDatePicker in an UIAlertController like manner

RMDateSelectionViewController This framework allows you to select a date by presenting an action sheet. In addition, it allows you to add actions arro

Roland Moers 1.2k Dec 13, 2022
This is an iOS control for selecting something using UIPickerView in an UIAlertController like manner

RMPickerViewController This framework allows you to pick something with a picker presented as an action sheet. In addition, it allows you to add actio

Roland Moers 382 Dec 19, 2022
SwiftUI native-like onboarding sheets

Welcome Sheet Welcome sheet for swiftUI enables incredibly easy way for creating onboarding screens, update notes, or whatever you imagine! The main i

Jakub Florek 43 Dec 29, 2022
A customizable framework to create draggable views

CFNotify CFNotify is written in Swift. Using UIKit Dynamics as animator. It can make ANY UIView object draggable and throwable. This library mainly us

Johnny Tsoi 491 Nov 20, 2022
A customizable framework to create draggable views

CFNotify CFNotify is written in Swift. Using UIKit Dynamics as animator. It can make ANY UIView object draggable and throwable. This library mainly us

Johnny Tsoi 491 Nov 20, 2022
Native alert from Apple Music & Feedback. Contains Done, Heart & Message and other presets. Support SwiftUI.

SPAlert Popup from Apple Music & Feedback in AppStore. Contains Done, Heart, Error and other presets. Supports Dark Mode. I tried to recreate Apple's

Ivan Vorobei 1.4k Dec 10, 2021
Animated alert library like Swarm app.

TKSwarmAlert Animation Tool for Alert like Swarm app. ScreenShot Installation CocoaPods You can use CocoaPods to install TKSwarmAlert by adding it to

Takuya Okamoto 581 Dec 2, 2022