Skip to content

Instantly share code, notes, and snippets.

@arunavo4
Last active September 21, 2025 10:41
Show Gist options
  • Select an option

  • Save arunavo4/8eedb035ce6565cbc74038537a57a6d7 to your computer and use it in GitHub Desktop.

Select an option

Save arunavo4/8eedb035ce6565cbc74038537a57a6d7 to your computer and use it in GitHub Desktop.
Toolbar search Swift UI iOS 26
//
// TestView.swift
//
// Created by Arunavo Ray on 21/09/25.
//
import SwiftUI
struct TestView: View {
@State private var searchText = ""
@State private var isSearching = false
let items = ["Apple", "Banana", "Orange", "Grape"]
var filteredItems: [String] {
if searchText.isEmpty {
return items
} else {
return items.filter { $0.localizedCaseInsensitiveContains(searchText) }
}
}
// Extract the navigation content so we can conditionally apply .searchable
private var navigationContent: some View {
NavigationStack {
List {
ForEach(filteredItems, id: \.self) { item in
Text(item)
}
}
.navigationTitle("Fruits")
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button {
isSearching = true
} label: {
Image(systemName: "magnifyingglass")
}
.accessibilityLabel("Search")
}
}
}
}
var body: some View {
Group {
if isSearching {
navigationContent
.searchable(
text: $searchText,
isPresented: $isSearching,
placement: .navigationBarDrawer(displayMode: .automatic),
prompt: "Search fruits"
)
.onSubmit(of: .search) {
// Collapse/minimize after submitting a query
isSearching = false
}
} else {
navigationContent
}
}
.onChange(of: isSearching) { wasSearching, nowSearching in
// Optional: clear when the search UI is dismissed
if wasSearching && !nowSearching {
searchText = ""
}
}
}
}
#Preview {
TestView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment