
SwiftUI is a powerful tool, though one area ripe for improvement is the variety of components available. In this post, we’ll explore how to build a custom component: a search text field.
Adding a searchable component in SwiftUI is straightforward — you can easily add a search field to the navigation bar with just one line of code. However, the challenge arises when you want to place this component in the middle of the screen or in any position other than the navigation bar. For such custom requirements, you’ll need to build it yourself. Let me show you one possible way to achieve this.
The GOAL
To construct our custom search text field, we require three key components:
- Image: To serve as the search icon, visually indicating the purpose of the text field.
- TextField: This is where the user will input their search query. It’s the core component of our search functionality.
- Button: A clear to clear the current input in the text field.
struct CustomSearchView: View {
@State var searchText: String = ""
var onSubmit: (String) -> Void
var body: some View {
HStack {
Image(systemName: "magnifyingglass")
.resizable()
.frame(width: 20, height:20)
.foregroundStyle(Color(.systemGray))…