GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

.searchable and managing focus

Forums > SwiftUI

Hi, does anybody know how to make the.searchable textfield have focus? It's a search view, so it makes sense to automatically make it have focus when it loads, but .focusState doesn't seem to work with it? Any ideas would be appreciated!

struct CustomerSearchView: View {
    @Binding var customer: Customer?

    @State private var searchName = ""
    @Environment(\.presentationMode) var presentationMode
    @EnvironmentObject var customerSearchViewModel: CustomerSearchViewModel
    @FocusState private var searchFocused: Bool

    var body: some View {
        NavigationStack {
            List {
                if customerSearchViewModel.shouldShowNoResults {
                    Text("🤔 No Results")
                } else if customerSearchViewModel.shouldShowProgressView {
                    ProgressView()
                }

                ForEach(customerSearchViewModel.customers) { searchResult in
                    SearchResultItemView(searchResult: searchResult)
                        .onTapGesture {
                            self.customer = searchResult
                            presentationMode.wrappedValue.dismiss()
                        }
                }
            }
            .searchable(text: $customerSearchViewModel.searchText, prompt: "Search by name, email or postcode")
            .focused($searchFocused)
            .autocorrectionDisabled(true)
            .keyboardType(.alphabet)                // stop keyboard suggestions
            .textContentType(.init(rawValue: ""))   // stop keyboard suggestions
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) {
                    searchFocused = true
                }
            }
            .onDisappear {
                customerSearchViewModel.searchText = ""
                customerSearchViewModel.customers.removeAll()
            }
        }
        .alert(isPresented: $customerSearchViewModel.hasError, error: customerSearchViewModel.error) { }
    }
}

3      

I'm assuming that I'm missing some nuance since I'm still pretty new to this, but I came accross your question when I had the same challenge. I found an answer in Apple's docs that is working well for me:

struct SheetView: View {
    @State private var isPresented = true
    @State private var text = ""

    var body: some View {
        NavigationStack {
            SheetContent()
                .searchable(text: $text, isPresented: $isPresented)
        }
    }
}  

I realize it is way to late to solve your problem but perhaps anyone else coming across this might benefit.

7      

That works. It was very helpful.

You can do it with a little less code with

   isPresented: .constant(true)

   

It looks like you’re on the right track with using @FocusState to manage focus for your search field. Just make sure your searchFocused state is being set to true properly. You might also want to check if the searchable modifier is compatible with focus state in your version of SwiftUI. If you're still having trouble, consider explicitly calling .focus() on the text field when the view appears. That could help ensure it gains focus automatically!

   

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Transform your career with the iOS Lead Essentials. This Black Friday, unlock over 40 hours of expert training, mentorship, and community support to secure your place among the best devs. Click for early access to this limited offer and a free crash course.

Save your spot

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.