1

In the native Settings app, there's a NavigationView with a TextField inside of it that nicely transitions as the user scrolls:

enter image description here

I was able to create something similar using:

struct HomeView: View {
    @State var searchQuery: String = ""

    var body: some View {
        NavigationView {
            List {
                TextField("Search", text: $searchQuery).textFieldStyle(RoundedBorderTextFieldStyle())
            }
            .navigationBarTitle(Text("My App"))
        }
    }
}

which gave me this:

enter image description here

However, this doesn't really look or act the same as the native settings one, and I'm lost on how to even get the search icon in there. Thanks so much!

Kyle Horkley
  • 911
  • 1
  • 9
  • 23

1 Answers1

3

What youre trying to create in SwiftUI would be a UISearchBar in swift's UIKit.

So you need to stylize the textfield

            TextField("Search ...", text: $text)
            .padding(7)
            .padding(.horizontal, 25)
            .background(Color(.systemGray6))
            .cornerRadius(8)
            .padding(.horizontal, 10)
            .onTapGesture {
                self.isEditing = true
            }

And in order to achieve the magnifying glass icon which is standard for a UISearchBar item. We need to add them manually with an overlay in SwiftUI

.overlay(
HStack {
    Image(systemName: "magnifyingglass")
        .foregroundColor(.gray)
        .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
        .padding(.leading, 8)

    if isEditing {
        Button(action: {
            self.text = ""
        }) {
            Image(systemName: "multiply.circle.fill")
                .foregroundColor(.gray)
                .padding(.trailing, 8)
        }
    }
}

)

you can reference this article for more https://www.appcoda.com/swiftui-search-bar/

Kev
  • 62
  • 2
  • 2
    This answer helps with the static look of the searchbar, but does not answer how to get the searchbar to "act" the same as the native one the OP asked for. Eg. 1. when scrolling down the settings screen the searchbar animates away. 2. When the searchbar becomes active it animates to the top while the navigation view animates away. – TimBigDev Mar 17 '21 at 21:44