I am using the new searchable modifier: https://developer.apple.com/documentation/swiftui/form/searchable(text:placement:). When a user enters the view with a that modifier, that text field is not automatically focussed.
Is there a way to get focus on the searchable? This is my view, it is called with NavigationLink
import SwiftUI
struct UserFindView: View {
@State private var searchText = ""
var body: some View {
Text("Please search")
.searchable(text: $searchText)
.navigationTitle("Title")
.navigationBarTitleDisplayMode(.inline)
}
}
As of iOS 17 you can now use .searchable(text: Binding<String>, isPresented: Binding<Bool>)
struct ContentView: View {
@State private var searchText = ""
@State private var isSearching = false
private let fruits = ["apple", "banana", "plum", "grape"]
var filteredFruits: [String] {
if !searchText.isEmpty {
return fruits.filter { $0.starts(with: searchText.lowercased()) }
} else {
return fruits
}
}
var body: some View {
NavigationView {
List {
ForEach(filteredFruits, id: \.self) { fruit in
Text(fruit.capitalized)
}
}
.navigationBarTitle("Search")
.searchable(text: $searchText, isPresented: $isSearching)
Button("Search", action: { isSearching = true})
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With