I am trying to set the focus on the .searchable text entry field using @FocuseState and .focused($focusedField, equals: .search) technique demonstrated by Tanu in her WWDC21-10023 talk, but I'm not sure if it is a focusable element or how to programmatically set it. My attempt:
//based on a technique presented in https://developer.apple.com/videos/play/wwdc2021/1002 and Paul Hudson's article https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-a-search-bar-to-filter-your-data
import SwiftUI
enum Field: Hashable {
case search
}
struct ContentView: View {
let itemsToSearch = ["John", "Mark", "Adam", "Carol", "Ismael", "Vanessa", "Aniq"]
@FocusState private var focusedField: Field?
@State private var searchText = ""
var body: some View {
NavigationView {
List {
ForEach(searchResults, id: \.self) { itemsToSearch in
NavigationLink(destination: Text(itemsToSearch)) {
Text(itemsToSearch)
}
}
}
.searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always)) {
ForEach(searchResults, id: \.self) { result in
Text("\(result)").searchCompletion(result)
}
.focused($focusedField, equals: .search)
.onAppear {
focusedField = .search
}
}
}
}
var searchResults: [String] {
if searchText.isEmpty {
return itemsToSearch
} else {
return itemsToSearch.filter { $0.contains(searchText) }
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Can someone clarify if this is possible, and if so, where I am going wrong? Thanks in advance.
Laith