DEV Community

Cover image for Building Alerts in iOS 18 - #30DaysOfSwift
Vaibhav Dwivedi
Vaibhav Dwivedi

Posted on

2

Building Alerts in iOS 18 - #30DaysOfSwift

Day 16: Alerts – Designing Native Alerts in SwiftUI 🚨

Today, we’ll focus on using the native alert options available in SwiftUI.

SwiftUI provides a straightforward way to display alerts like this:

Image description

Why Use Native Alerts?

  • Simplicity: SwiftUI’s native alerts are easy to implement and require minimal code.
  • System Integration: They provide a familiar look and feel, ensuring consistency across iOS applications.
  • Accessibility: Native alerts come with built-in accessibility support, making your app more user-friendly.

Code Example: Creating a Native Alert

import SwiftUI

struct ContentView: View {
    @State private var showAlert = false // State variable to control alert visibility

    var body: some View {
        VStack {
            Button("Show Alert") {
                showAlert.toggle() // Toggle alert visibility
            }
            .alert(isPresented: $showAlert) { // Present the alert when showAlert is true
                Alert(
                    title: Text("Alert Title"), // Title of the alert
                    message: Text("This is an alert message."), // Message to display
                    primaryButton: .default(Text("Confirm")) {
                        // Action to perform on Confirm
                        print("Confirmed!")
                    },
                    secondaryButton: .cancel() // Action to perform on Cancel
                )
            }
        }
        .padding()
    }
}
Enter fullscreen mode Exit fullscreen mode

Try implementing native alerts in your app to manage user interactions effectively!

The full series is available on my profile and the components can also be found at shipios.app/components.

Happy Coding! 🎉

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free