SwiftUI – How to show an Alert

By | 03/02/2021

In this post, we will see how to implement an Alert in SwiftUI.

We create a project called AlertTest and add this code in the file ContentView:

[CONTENTVIEW.SWIFT]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import SwiftUI
 
struct ContentView: View {
    // definition of variables used to manage Alert and show the date
    @State private var showAlert = false
    @State private var today = ""
     
    // function used to get the current date
    func ShowDate() {
        // get the current date and time
        let currentDateTime = Date()
 
        // initialize the date formatter and set the style
        let formatter = DateFormatter()
        formatter.timeStyle = .medium
        formatter.dateStyle = .long
 
        // get the date time String from the date object
        today = formatter.string(from: currentDateTime)
    }
     
    // function used to change the value of showAlert variable
    func ShowWindow() {
        self.showAlert = true
    }
     
    var body: some View {
        ZStack {
             
            // Definition background color
            Color.green.edgesIgnoringSafeArea(.all)
             
            VStack{
                Spacer()
                // button definition
                Button(action: ShowWindow) {
                               Text("ShowWindow")
                           }
                           .frame(width: 200, height: 30)
                           .background(Color.blue)
                           .foregroundColor(Color.white)
                           .cornerRadius(35)
                 
                // Text used to show the date
                Text(self.today)
                    .padding()
                Spacer()
                     
                // Alert definition
                // the "Yes" button calls the function ShowDate()
                .alert(isPresented: $showAlert) {
                    Alert(title: Text("Title Window"), message: Text("Do you want to show the current date?"), primaryButton: .default(Text("Yes"), action: { self.ShowDate() }), secondaryButton: .cancel(Text("No")))
                }
            }
        }
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}



This is all and now, if we run the application, this will be the result:



Leave a Reply

Your email address will not be published. Required fields are marked *