Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus automatically on searchable

Tags:

swift

swiftui

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)
    }
}
like image 368
NoKey Avatar asked Feb 15 '26 14:02

NoKey


1 Answers

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})
        }
    }
}
like image 199
Daniel Avatar answered Feb 17 '26 05:02

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!