skip to Main Content

I am using the .searchable modifier in SwiftUI. Is there anyway to know when the user presses the search key on the keyboard?
I know how to do this by using a UIViewRepresentable and searchController. I’m wondering if there is a SwiftUI way of doing it with the .searchable modifier

2

Answers


  1. This is still beta in macOS 12 (but not i/iPad/tvOS 15) as I write this so not really for this forum, however…

    searching has an instance property:

    var isSearching: Bool { get }

    which can be passed into a child view using:

    @Environment(.isSearching) var isSearching

    and subsequently interrogated from that var

    Look up the Apple documentation

    Login or Signup to reply.
  2. Add an .onSubmit(of: .search) modifier. Like this:

        List {
            ForEach(results, id: .self) { result in
               Text(result)
            }
        }
        .searchable(text: $searchText)
        .onSubmit(of: .search) {
         // Search button tapped. Perform operation here
        }
    

    If if works for you, mark as correct answer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search