SwiftUI series 8: Building a Switch Tab Demo in SwiftUI

In this tutorial, we'll walk through creating a simple yet effective search interface using SwiftUI. We'll build a main content view that allows users to switch between two different search implementations.

Understanding the Code Structure

Let's break down the main components of our ContentView:

struct ContentView: View {
    @State private var selectedDemo = 0

    var body: some View {
        NavigationStack {
            // Main content here
        }
    }
}

Key Components:

  1. State Management

    @State private var selectedDemo = 0

    We use a @State property wrapper to maintain the selected search view option. The initial value is 0, representing the basic search view.

  2. Navigation Stack The entire content is wrapped in a NavigationStack, providing a foundation for navigation capabilities.

  3. Segmented Control

    Picker("Select Views", selection: $selectedDemo) {
    Text("Basic Search").tag(0)
    Text("Better Search").tag(1)
    }
    .pickerStyle(.segmented)
    .padding()

    This creates a segmented control with two options: "Basic Search" and "Better Search". The selection is bound to our selectedDemo state variable.

  4. Conditional View Rendering

    if selectedDemo == 0 {
    SearchView()
    } else {
    BetterSearchView()
    }

    Based on the selected option, we display either the basic SearchView or the enhanced BetterSearchView.

Customization and Styling

The picker is styled using .pickerStyle(.segmented) for a clean, iOS-native look, and padding is added for better spacing.

Preview

The preview is set up simply with:

#Preview {
    ContentView()
}

Usage

This view serves as the main container for our search functionality, allowing users to toggle between two different search implementations. The segmented control provides an intuitive way to switch between views.

Next Steps

In the following tutorials, we'll dive into implementing betterSearchView components