article

Wednesday, May 5, 2021

SwiftUI How to show alert

SwiftUI How to show alert

Basic SwiftUI alerts look like this:

Alert(title: Text("This is a message"), message: Text("succcess message"), dismissButton: .default(Text("Got it!")))
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders 
//

import SwiftUI

struct ContentView: View {
    
    @State private var showAlert = false
    
    var body: some View {
        
        Button("Show Alert") {
            showAlert = true
        }
        .alert(isPresented: $showAlert) {
            Alert(title: Text("Important message"), message: Text("this is a success messge"), dismissButton: .default(Text("Got It!")))
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
        
    }
}
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders
//

import SwiftUI

struct Swifuiprogram: Identifiable {
    var id: String { name }
    let name: String
}
struct ContentView: View {
    
    @State private var selecprogramming: Swifuiprogram?
    var body: some View {
        VStack(spacing: 20) {
            Text("What is your programming language")
                .font(.headline)
            
            Button("Select SwiftUI") {
                selecprogramming = Swifuiprogram(name: "SwiftUI")
            }
            
            Button("Select IOS") {
                selecprogramming = Swifuiprogram(name: "IOS")            }
        }
        .alert(item: $selecprogramming) { show in
            Alert(title: Text(show.name), message: Text("Great choice"), dismissButton: .cancel())
        }

    }
}

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

Related Post