DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


How to show an alert in SwiftUI?

  • 4 minutes read
  • 2266 Views
How to show an alert in SwiftUI?

    Table of Contents

How to show an alert in SwiftUI?

When we use SwiftUI, we can show alerts to the user with the alert() modifier. How that works depends on whether we want to target iOS 15 and later or iOS 13 and 14. I’ll show you both ways, but the newer iOS 15 method is better because it builds on standard SwiftUI buttons.

How to show an alert in iOS 15 and above?

Let’s start with iOS 15 first. In order to show an alert, you need to make a Boolean state that tells you if the alert should be visible. Then, attach that to an alert() modifier, along with all the buttons you want to show in the alert. In this case, you can make an empty button that will just dismiss the alert.

Suppose this shows an alert with only one “OK” button.

** Note :- When the button is tapped, showAlert will be set to false and the alert will be dismissed.


struct ContentView: View {
    @State private var showAlert = false

    var body: some View {
        Button("Show Alert") {
            showAlert = true
        }
        .alert("Important alert", isPresented: $showAlert) {
            Button("OK", role: .cancel) { }
        }
    }
}

how_to_show_alerts_in_swiftUI_giphy.gif

How does .alert() modifier works on iOS 15?

We used the .alert modifier, which has three parameters: a title parameter for the title of the alert; an isPresented parameter that is a binding to a Boolean value that tells us whether the alert is shown or hidden; and one closure, action, that tell us what to do. The action parameter is a ViewBuilder that returns the alert’s actions.

The OK button now has a .cancel role attached to it. SwiftUI creates and displays a .cancel button in the alert if it is not already assigned to a role.

Hence, removing the Ok button will still give you the same result

.alert("Important alert", isPresented: $showAlert) {
            // Remove the OK button from here
        }

How to add more than one button to alert?

You can add as many buttons as you would like to in a SwiftUI alert.


struct ContentView: View {
    @State private var showAlert = false

    var body: some View {
        Button("Show Alert") {
            showAlert = true
        }
        .alert("Important alert", isPresented: $showAlert) {

            Button("One") {}
            Button("Two") {}
            Button("Three") {}
            Button("Cancel", role: .cancel){}

        }
    }
}

alert_with_multiple_buttons.gif

Having more than two buttons place them vertically but if there are only two buttons, SwiftUI will place them horizontally.

two_buttons_alert.gif

How to show an alert in iOS 14 & iOS 13?

If you require support for iOS 14 and 13, you should instead use the dedicated Alert struct, which has the following structure:

Alert(
    title: Text("Important Alert"),
    message: Text("This is an alert for iOS 14 & 13"), 
    dismissButton: .default(Text("OK"))
)

This defines a title and message, similar to those found in a UIAlertController, and then adds a dismiss button with the default style and text “Ok”

To demonstrate that alert, the first step is to define a bindable condition that determines whether or not the alert should be visible. You then associate that with your main view, which displays the alert when its condition is met.

For instance, the following code creates a showiAlert Boolean that determines whether the alert message should be displayed or not, sets it to true when a button is tapped, and then creates and attaches an alert view to the showAlert Boolean so it appears when the button is tapped:



struct ContentView: View {
    @State private var showAlert = false

    var body: some View {
        Button("Show Alert") {
            showAlert = true
        }
        .alert(isPresented: $showAlert) {
            Alert(
                title: Text("Important Alert"),
                message: Text("This is an alert for iOS 14 & 13"),
                dismissButton: .default(Text("OK"))
            )

        }
    }
}

How does alerts work in iOS 14 & iOS 13?

The process of displaying alerts is three-step. To begin, we create a @State variable whose value is used to determine whether the alert should be displayed or hidden. Then, we add an.alert() modifier to the view that is being modified. Finally, we incorporate an Alert view within the .alert() modifier. The showAlert state variable is passed to the modifier’s isPresented argument in this code. When showAlert is set to true, the alert is displayed. When the user clicks the OK button in the Alert view, the value of the button changes back to false, and the alert is once again hidden. We used an Alert view with three parameters: the title of the alert, a message, and a Button that, when clicked, dismissed the alert.


Related Posts

How to create a List View in Swift UI without using MVVM ? 2022
By Udit Vashisht

How to start a new iOS project in Xcode?

To create a new ios project, Open Xcode on your Mac and click on ‘Create a New Xcde Project’

create-a-new-xcode-project-swift-ui.png

In the next window, select ‘ios’ from the top menu and then select ‘App’ and click on Next

...

Read More
How to show a Popup alert on First Launch of an app in Swift UI?
By Udit Vashisht

How to create a pop-up alert/ display alert in SwiftUI?

In this tutorial, we will learn to show/create a pop up alert on the first launch of Swift UI. I hope that you all know how to start a new project in Swift UI, if not, you can refer to ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python how to learn python learn python