Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I present a UIAlertController in SwiftUI?

Tags:

swift

swiftui

In UIKit, it is common to present UIAlertController for modal pop up alert messages in response to some action.

Is there a modal alert controller type in SwiftUI?

Is there a way to present a UIAlertController from SwiftUI classes? It seems like this may be possible using UIViewControllerRepresentable but not sure if that is required?

like image 962
myuiviews Avatar asked Dec 22 '22 20:12

myuiviews


1 Answers

Use Alert instead.

import SwiftUI

struct SwiftUIView: View {
    @State private var showAlert = false;

    var body: some View {
        Button(action: { self.showAlert = true }) {
            Text("Show alert")
        }.alert(
            isPresented: $showAlert,
            content: { Alert(title: Text("Hello world")) }
        )
    }
}

Bind to isPresented in order to control the presentation.

like image 111
EvZ Avatar answered Jan 17 '23 21:01

EvZ