article

Wednesday, May 5, 2021

SwiftUI How to add actions to alert buttons

SwiftUI How to add actions to alert buttons

SwiftUI How to add actions to alert buttons

this example if you want to attach actions to buttons to perfom specific actions
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders on 5/5/21.
//

import SwiftUI

struct ContentView: View {

    @State private var showingAlert = false

    var body: some View {
	
        Button("Show Alert") {
            showingAlert = true
        }
        .alert(isPresented:$showingAlert) {
            Alert(
                title: Text("Are you sure you want to delete this?"),
                message: Text("There is no undo"),
                primaryButton: .destructive(Text("Delete")) {
                    print("Deleted")
                },
                secondaryButton: .cancel()
            )
        }
    }
}

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

Related Post