← Back to Home

Essential SwiftUI UI Elements: Alerts, Toggles, and Buttons

SwiftUI UI Elements iOS

SwiftUI provides a rich set of UI elements for building interactive iOS applications. In this post, we'll explore three essential UI elements: alerts, toggle switches, and buttons. We'll look at various ways to implement and customize them.

1. Presenting Alerts in SwiftUI

Alerts are crucial for displaying important messages and getting user confirmation. SwiftUI offers several ways to present alerts.

Basic Alert

BasicAlert.swift
struct ContentView: View {
    @State private var showingAlert = false
    
    var body: some View {
        Button("Show Alert") {
            showingAlert = true
        }
        .alert("Important Message", isPresented: $showingAlert) {
            Button("OK", role: .cancel) { }
        } message: {
            Text("This is a basic alert message.")
        }
    }
}

Alert with Multiple Actions

AlertWithActions.swift
struct AlertWithActions: View {
    @State private var showingAlert = false
    
    var body: some View {
        Button("Delete Item") {
            showingAlert = true
        }
        .alert("Confirm Deletion", isPresented: $showingAlert) {
            Button("Delete", role: .destructive) {
                // Handle deletion
            }
            Button("Cancel", role: .cancel) { }
        } message: {
            Text("This action cannot be undone.")
        }
    }
}

Custom Alert with Error Handling

ErrorAlert.swift
enum NetworkError: Error, LocalizedError {
    case connectionFailed
    case invalidResponse
    
    var errorDescription: String? {
        switch self {
        case .connectionFailed:
            return "Unable to connect to the server"
        case .invalidResponse:
            return "Invalid server response"
        }
    }
}

struct ErrorHandlingView: View {
    @State private var error: NetworkError?
    
    var body: some View {
        Button("Fetch Data") {
            error = .connectionFailed // Simulate error
        }
        .alert("Error", isPresented: Binding(
            get: { error != nil },
            set: { if !$0 { error = nil } }
        )) {
            Button("OK") {
                error = nil
            }
        } message: {
            Text(error?.localizedDescription ?? "")
        }
    }
}

2. Toggle Switch and Checkbox

Toggles are essential for binary choices in your app. SwiftUI provides multiple ways to implement them.

Basic Toggle Switch

BasicToggle.swift
struct SettingsView: View {
    @State private var isNotificationsEnabled = false
    
    var body: some View {
        Toggle("Enable Notifications", isOn: $isNotificationsEnabled)
            .padding()
            .onChange(of: isNotificationsEnabled) { newValue in
                // Handle toggle change
                print("Notifications enabled: \(newValue)")
            }
    }
}

Custom Checkbox

CustomCheckbox.swift
struct Checkbox: View {
    let title: String
    @Binding var isChecked: Bool
    
    var body: some View {
        Button(action: {
            isChecked.toggle()
        }) {
            HStack {
                Image(systemName: isChecked ? "checkmark.square.fill" : "square")
                    .foregroundColor(isChecked ? .blue : .gray)
                
                Text(title)
                    .foregroundColor(.primary)
            }
        }
    }
}

// Usage Example
struct CheckboxDemo: View {
    @State private var isAgreed = false
    
    var body: some View {
        Checkbox(title: "I agree to terms", isChecked: $isAgreed)
            .padding()
    }
}

3. SwiftUI Buttons

Buttons are fundamental to user interaction. SwiftUI offers various ways to create and style buttons.

Basic Buttons

ButtonStyles.swift
struct ButtonDemo: View {
    var body: some View {
        VStack(spacing: 20) {
            // Basic Button
            Button("Basic Button") {
                print("Button tapped")
            }
            
            // Styled Button
            Button("Styled Button") {
                print("Styled button tapped")
            }
            .buttonStyle(.bordered)
            .tint(.blue)
            
            // Custom Style
            Button(action: {
                print("Custom button tapped")
            }) {
                Text("Custom Button")
                    .fontWeight(.semibold)
                    .foregroundColor(.white)
                    .padding()
                    .background(.blue)
                    .cornerRadius(10)
            }
        }
        .padding()
    }
}

Button with Icon

IconButton.swift
struct IconButtonDemo: View {
    var body: some View {
        Button(action: {
            // Handle action
        }) {
            HStack(spacing: 8) {
                Image(systemName: "plus.circle.fill")
                Text("Add Item")
            }
            .padding()
            .background(.blue)
            .foregroundColor(.white)
            .cornerRadius(8)
        }
    }
}

Custom Button Style

CustomButtonStyle.swift
struct GradientButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding()
            .background(
                LinearGradient(
                    gradient: Gradient(colors: [.blue, .purple]),
                    startPoint: .leading,
                    endPoint: .trailing
                )
            )
            .foregroundColor(.white)
            .cornerRadius(10)
            .scaleEffect(configuration.isPressed ? 0.95 : 1.0)
            .animation(.easeInOut, value: configuration.isPressed)
    }
}

// Usage
struct CustomButtonDemo: View {
    var body: some View {
        Button("Gradient Button") {
            print("Tapped!")
        }
        .buttonStyle(GradientButtonStyle())
    }
}

Best Practices

  • Use meaningful alert titles and messages
  • Provide clear feedback for toggle states
  • Ensure buttons have appropriate hit targets
  • Consider accessibility when customizing controls
  • Use system-provided styles when possible for consistency

Conclusion

These UI elements form the foundation of interactive iOS applications. SwiftUI makes it easy to implement and customize them while maintaining a native feel. Remember to consider accessibility and user experience when implementing these controls in your apps.