avatarStephanie De Smedt

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3176

Abstract

matching items as the user types.</p><p id="1b05">To create this dynamic list this we start with an if-statement that displays the whole list if no text has been inputted. Then an else-statement that makes use of the built-in array method “filter” to only display those items that contain the search text.</p><div id="a343"><pre><span class="hljs-keyword">var</span> searchResults: [<span class="hljs-type">String</span>] { <span class="hljs-keyword">if</span> searchText.isEmpty { <span class="hljs-keyword">return</span> foods } <span class="hljs-keyword">else</span> { <span class="hljs-keyword">return</span> foods.filter { <span class="hljs-variable">0</span>.contains(searchText) } } }</pre></div><h2 id="b1cb">Step 3: Create a List to display search results</h2><p id="b6bc">The dynamic search results variable will be the information that we want to display on the page. To display this we make use of SwiftUIs List functionality but embed within it a ForEach loop to iterate over the searchResults array.</p><div id="4448"><pre><span class="hljs-type">List</span> { <span class="hljs-type">ForEach</span>(searchResults, id: \.<span class="hljs-keyword">self</span>) { food <span class="hljs-keyword">in</span> <span class="hljs-type">Text</span>(food) } }</pre></div><p id="2c19">In this example the result was kept simple, however it is more common to use a Navigation View at this stage and let users click on the item they require and progress to another view within your app — or some other interactive functionality that suits your purpose.</p><h2 id="052b">Step 4: Add the searchable text filter</h2><p id="4269">At this stage the list will appear in the view but there is no means of entering in the search text to filter it. This step is made simple thanks to a List modifier that exists within the Swift syntax — the <a href="https://developer.apple.com/documentation/swiftui/view/searchable(text:placement:prompt:)-18a8f">searchable</a> modifier.</p><p id="6dd1">The searchable modifier takes a string variable as a binding parameter and then searches the list for the content within it.</p><div id="8c25"><pre>.searchable(text: <span class="hljs-variable">searchText</span>)</pre></div><h2 id="bf9d">Step 5: Customize the view</h2><p id="c754">Now all the functionality needed to create a basic searchable list that filters as the user types in place. At this point you can now customize your view by adding in padding, background colors or any other alterations.</p><h1 id="44e1">Sample Code</h1><p id="3370">Below is the Sample Code putting together all of the steps above:</p><div id="35ae"><pre><span class="hljs-keyword">struct</span> <span class="hljs-title class_">SearchableListView</span>: <span class="hljs-title class_">View</span> {

<span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> foods <span class="hljs-operator">=</span> [<span class="hljs-string">"Cheese"</span>,<span class="hljs-string">"Milk"</span>,<span class="hljs-string">"Cauliflower"</span>,<span class="hljs-string">"Cabbage"</span>,<span class="hljs-string"

Options

"Carrots"</span>,<span class="hljs-string">"Wine"</span>,<span class="hljs-string">"Bacon"</span>,<span class="hljs-string">"Olives"</span>,<span class="hljs-string">"Yoghurt"</span>,<span class="hljs-string">"Apples"</span>,<span class="hljs-string">"Bananas"</span>,<span class="hljs-string">"Oranges"</span>,<span class="hljs-string">"Pasta"</span>,<span class="hljs-string">"Rice"</span>,<span class="hljs-string">"Soy Sauce"</span>, <span class="hljs-string">"Chicken"</span>,<span class="hljs-string">"Chives"</span>,<span class="hljs-string">"Potato"</span>,<span class="hljs-string">"Sparkling Water"</span>,<span class="hljs-string">"Coffee"</span>] <span class="hljs-meta">@State</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> searchText <span class="hljs-operator">=</span> <span class="hljs-string">""</span>

<span class="hljs-keyword">var</span> body: <span class="hljs-keyword">some</span> <span class="hljs-type">View</span> {
    
    <span class="hljs-type">VStack</span>{
        <span class="hljs-type">NavigationView</span>{
            
            <span class="hljs-type">List</span> {
                <span class="hljs-type">ForEach</span>(searchResults, id: \.<span class="hljs-keyword">self</span>) { food <span class="hljs-keyword">in</span>
                    <span class="hljs-type">Text</span>(food)
                }
                
                }.searchable(text: <span class="hljs-variable">$searchText</span>)
        }
        .padding()
    }
}

<span class="hljs-comment">//Show the entire list if search field is blank else show compatible items</span>
<span class="hljs-keyword">var</span> searchResults: [<span class="hljs-type">String</span>] {
    <span class="hljs-keyword">if</span> searchText.isEmpty {
        <span class="hljs-keyword">return</span> foods
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> foods.filter { <span class="hljs-variable">$0</span>.contains(searchText) }
    }
}

}</pre></div><p id="bd14">There you have it!… A searchable list to allow users to navigate your app better. This was just a simple example, but it can of course be extended to give more complicated outcomes depending on the needs of your application.</p><p id="4bab">I'd love to hear for you if this helped and how you plan on using it in your own projects. Let me know in the comments if you have any questions or suggestions on this topic!</p><blockquote id="f243"><p><b><i>Thanks for reading! If you liked this post and want to read more, be sure to check out my profile or <a href="https://medium.com/subscribe/@simply_stef">subscribe</a> for similar posts.</i></b></p></blockquote><blockquote id="4760"><p><b><i>Subscribe to Medium to gain unlimited access to all the content and ideas available. <a href="https://medium.com/@simply_stef/membership">If you join Medium through this link I will receive a tiny amount from your fees — and it will not cost you any extra!</a></i></b></p></blockquote></article></body>

Building a Searchable List with SwiftUI

Create a Searchable List with Autocomplete functionality for your iOS App

One of the big challenges when designing a new app is ensuring that your users can navigate around the content easily. If the experience is too difficult or takes too much time a lot of users will move onto another app option or give up no matter how good your content is.

Expecting a user to scroll through a long list of options is not practical and adding a search functionality can greatly improve the user experience. Taking this further having the list auto-filter as the user types to help them quickly find what they are searching for is even better.

Below is a step-by-step guide to building just that for your iOS projects. We will walk through how to build a searchable list of items that is filtered as the user types with SwiftUI… I have also included some sample code to get you started at the end of the post.

Step 1: Create an Array of Items

First, create the list of items that the user will want to search through.

This list can be of any data type, including custom ones. In our basic example we will build a searchable grocery list, so will be using a list of strings.

var foods = ["Cheese","Milk","Cauliflower","Cabbage","Carrots","Wine","Bacon",
     "Olives","Yoghurt","Apples","Bananas","Oranges","Pasta","Rice","Soy Sauce",
     "Chicken","Chives","Potato","Sparkling Water","Coffee"]

Step 2: Create search variables

The next step is to create two different variables. The first one will contain the string that user inputs to search the list. Since this will change depending on user input it should be a State variable:

@State private var searchText = ""

The second is a dynamic subset of the full list created in step one. This variable will display the full list of items if no search term has been entered but will update to display matching items as the user types.

To create this dynamic list this we start with an if-statement that displays the whole list if no text has been inputted. Then an else-statement that makes use of the built-in array method “filter” to only display those items that contain the search text.

var searchResults: [String] {
        if searchText.isEmpty {
            return foods
        } else {
            return foods.filter { $0.contains(searchText) }
        }
    }

Step 3: Create a List to display search results

The dynamic search results variable will be the information that we want to display on the page. To display this we make use of SwiftUIs List functionality but embed within it a ForEach loop to iterate over the searchResults array.

List {
     ForEach(searchResults, id: \.self) { food in
         Text(food)
        }
     }

In this example the result was kept simple, however it is more common to use a Navigation View at this stage and let users click on the item they require and progress to another view within your app — or some other interactive functionality that suits your purpose.

Step 4: Add the searchable text filter

At this stage the list will appear in the view but there is no means of entering in the search text to filter it. This step is made simple thanks to a List modifier that exists within the Swift syntax — the searchable modifier.

The searchable modifier takes a string variable as a binding parameter and then searches the list for the content within it.

.searchable(text: $searchText)

Step 5: Customize the view

Now all the functionality needed to create a basic searchable list that filters as the user types in place. At this point you can now customize your view by adding in padding, background colors or any other alterations.

Sample Code

Below is the Sample Code putting together all of the steps above:

struct SearchableListView: View {
   
    private var foods = ["Cheese","Milk","Cauliflower","Cabbage","Carrots","Wine","Bacon","Olives","Yoghurt","Apples","Bananas","Oranges","Pasta","Rice","Soy Sauce",
                         "Chicken","Chives","Potato","Sparkling Water","Coffee"]
    @State private var searchText = ""
    
    var body: some View {
        
        VStack{
            NavigationView{
                
                List {
                    ForEach(searchResults, id: \.self) { food in
                        Text(food)
                    }
                    
                    }.searchable(text: $searchText)
            }
            .padding()
        }
    }
    
    //Show the entire list if search field is blank else show compatible items
    var searchResults: [String] {
        if searchText.isEmpty {
            return foods
        } else {
            return foods.filter { $0.contains(searchText) }
        }
    }
}

There you have it!… A searchable list to allow users to navigate your app better. This was just a simple example, but it can of course be extended to give more complicated outcomes depending on the needs of your application.

I'd love to hear for you if this helped and how you plan on using it in your own projects. Let me know in the comments if you have any questions or suggestions on this topic!

Thanks for reading! If you liked this post and want to read more, be sure to check out my profile or subscribe for similar posts.

Subscribe to Medium to gain unlimited access to all the content and ideas available. If you join Medium through this link I will receive a tiny amount from your fees — and it will not cost you any extra!

Swift
Swiftui
Programming
iOS App Development
Apps
Recommended from ReadMedium