Image generated with AI

Member-only story

Custom Component in SwifUI

Nicola De Filippo
2 min readJun 10, 2024

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:

  1. Image: To serve as the search icon, visually indicating the purpose of the text field.
  2. TextField: This is where the user will input their search query. It’s the core component of our search functionality.
  3. 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))
Nicola De Filippo
Nicola De Filippo

Written by Nicola De Filippo

Software Engineer and Entrepreneur

No responses yet

Write a response