The basic structure

For reusability, I create the search bar as a seperate view, but you can also implement it right into your view.

struct SearchBar: View {
	    var placeholder: String

	    @Binding var text: String

	    var body: some View {
	        TextField(placeholder, text: $text) 
	    }
	}

Now you have a simple TextField, but it doesn’t have any styling yet.

Image for post

SearchBar(placeholder: “Search …”, text: $text)


Clear button

The next thing we will add is a clear button, that sets the text back to "" .

HStack {
	    TextField(placeholder, text: $text)
	    if text != "" {
	        Image(systemName: "xmark.circle.fill")
	            .imageScale(.medium)
	            .foregroundColor(Color(.systemGray3))
	            .padding(3)
	            .onTapGesture {
	                withAnimation {
	                    self.text = ""
	                  }
	            }
	    }
	}

#ios #swift #xcode #swiftui

Create an iOS-styled Search Bar in SwiftUI
19.85 GEEK