48

SwiftUI Alert Tutorial

 4 years ago
source link: https://www.tuicool.com/articles/3yaqy2N
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

An Alert displays an alert message to the user. The alert will be displayed using the presentation method which can added to a view. In this tutorial we will display an alert when the user clicks a button.SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project . In the template selector, select iOS as the platform, select the Single View App template, and then click Next . Enter SwiftUIAlertTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next . Choose a location to save the project on your Mac.

VBBNB37.png!web

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

QF3Ibe3.png!web

In the Project navigator, click to select ContentView.swift . Change the code inside the ContentView struct to

struct ContentView : View {
    // 1.
    @State private var isShowingAlert = false
      
    var body: some View {
        // 2.
        Button(action: {
            self.isShowingAlert = true
        }) {
            Text("Show Alert")
        }
        // 3.
        .presentation($isShowingAlert) {
            Alert(title: Text("iOScreator"), message: Text("Hello SwiftUI"), dismissButton: .default(Text("Dismiss")))
        }
    }
}
  1. The state property is created to determine when the alert will be displayed

  2. A button is created, which will set the state property to true when clicked.

  3. The presentation method is called which will display the Alert.

In the preview pane enable the Live view and select the Show Alert button. The Alert will be displayed.

aEnyYvV.png!web

The source code of the SwiftUIAlertTutorial can be downloaded at the ioscreator repository on Github .


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK