HD Mavani
HD Mavani

Reputation: 81

How to create a Navigation Bar with a title, "Done" button and Segmented Picker in SwiftUI?

I'm trying to replicate a UI similar to the one in the Safari app on iOS (as shown in the attached image) using SwiftUI. The navigation bar includes:

enter image description here

Here's my current SwiftUI code:

import SwiftUI

enum Tab: String, CaseIterable {
    case bookmarks = "Bookmarks"
    case readingList = "Reading List"
    case history = "History"
    
    var icon: String {
        switch self {
        case .bookmarks: return "book"
        case .readingList: return "eyeglasses"
        case .history: return "clock"
        }
    }
}

struct ContentView: View {
    @State private var selectedTab: Tab = .bookmarks
    @State private var searchQuery = ""
    
    var body: some View {
        NavigationStack {
            VStack {
                ScrollView {
                    Text("Content for \(selectedTab.rawValue)")
                        .font(.title)
                        .padding()
                    
                    Spacer()
                }
            }
            .searchable(text: $searchQuery)
            .navigationTitle(selectedTab.rawValue)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                // Centered Segmented Picker
                ToolbarItem(placement: .principal) {
                    Picker("", selection: $selectedTab) {
                        ForEach(Tab.allCases, id: \.self) { tab in
                            Image(systemName: tab.icon)
                                .tag(tab)
                        }
                    }
                    .pickerStyle(SegmentedPickerStyle())
                }
                
                // "Done" Button
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("Done") {
                        print("Done tapped")
                    }
                }
            }
        }
    }
}

#Preview {
    ContentView()
}

However, the result does not match the desired UI:

The segmented picker is not properly aligned and does not replicate the Safari app’s appearance.

The search field is not integrated into the navigation bar as in Safari.

The "Done" button overlaps or misaligns with the segmented picker.

Upvotes: 1

Views: 60

Answers (0)

Related Questions