article

Monday, December 6, 2021

SwiftUI Simple Alert and Confirmation Dialog

SwiftUI Simple Alert and Confirmation Dialog

ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var deleteConfirm = false
    @State private var showingOptions = false
    @State private var selection = "None"
    
    var body: some View {
        VStack {
            Button {
                self.deleteConfirm.toggle()
            } label: {
                Label("Delete", systemImage: "trash.fill")
            }
            .buttonStyle(.bordered)
            .tint(.red)
            .controlSize(.regular)
            //.alert("Are you Sure you want to delete?", isPresented: self.$deleteConfirm) {
            //    Button("Delete", role: .destructive) {
            //        print("Deleted")
            //    }
            //}
            .confirmationDialog("Are you Sure you want to delete?", isPresented: self.$deleteConfirm, titleVisibility: .visible) {
                Button("Delete", role: .destructive) {
                    print("Deleted")
                }
            }
            
            Text(selection)

            Button("Confirm paint color") {
                showingOptions = true
            }
            .buttonStyle(.bordered)
            .tint(.red)
            .controlSize(.regular)
            
            .confirmationDialog("Select a color", isPresented: $showingOptions, titleVisibility: .visible) {
                Button("Red") {
                    selection = "Red"
                }

                Button("Green") {
                    selection = "Green"
                }

                Button("Blue") {
                    selection = "Blue"
                }
            }
            

        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Related Post