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 this post to check out how to create a brand new project in Swift UI
First of all open the ‘ContentView.swift’ file in your editor. It will look like this:-
// Created by Udit Vashisht on 18/01/22.
//
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
In order to show the display alert, first of all we will need to wrap our text into a Vstack, so hold the command key and left click on the Text and then choose embed in VStack
Now just outside the view struct declare a State variable ‘showAlert’ and set it as true
@State var showAlert = true
Now just outside the VStack add the code to show your alert. The alert would have three components - title, message and dismissButton
import SwiftUI
struct ContentView: View {
@State var showAlert = true
var body: some View {
VStack {
Text("Hello, world!")
.padding()
}.alert(isPresented: $showAlert)
{
Alert(title: Text("Welcome"),
message: Text("Welcome to my App"),
dismissButton: .default(Text("Okay")))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
So, this will now show you the alert on the screen. But till now it will always show the alert as we have set showAlert as true and has never changed its value after the first launch.
So, to do so we will first change teh showAlert to false and then we will @AppStorage wrapper to store a boolean called ‘firstLaunch’ and after the very first launch we will change it’s value to false and thus the alert would not be shown in future. So the two lines of code would be as under:-
@State var showAlert = false
@AppStorage("firstLaunch") var firstLaunch: Bool = true
Then we will create a function which will see if it is the very first launch, if it is, the function will change the value of showAlert to true, thus showing the alert. And, at last it would change the value of firstLaunch to false, so that the function is not run thereafter.
func show(){
if firstLaunch{
showAlert = true
firstLaunch = false
}
Thereafter, we will add an onAppear modifier to the VStack and the complete code would look as under
import SwiftUI
struct ContentView: View {
@State var showAlert = false
@AppStorage("firstLaunch") var firstLaunch: Bool = true
func show(){
if firstLaunch{
showAlert = true
firstLaunch = false
}
}
var body: some View {
VStack {
Text("Hello, world!")
.padding()
}.onAppear(perform: show)
.alert(isPresented: $showAlert)
{
Alert(title: Text("Welcome"),
message: Text("Welcome to my App"),
dismissButton: .default(Text("Okay")))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}