16

SwiftUI Search Bar Tutorial

 3 years ago
source link: https://www.ioscreator.com/tutorials/swiftui-search-bar-tutorial
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
SwiftUI Search Bar Tutorial

in SwiftUI a Search Bar can be displayed inside a List using the searchable modifier. When using the Search Bar the results will be displayed automatically. In this tutorial a list of countries is displayed and can be searched.This tutorial is built for iOS15 and Xcode 13, which can be download at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.

Enter SwiftUISearchBarTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbox and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the ContentView struct to

struct ContentView: View { // 1. let countries = ["Afghanistan", "Albania", "Algeria", "Angola", "Argentia", "Armenia", "Australia", "Austria"] // 2. @State private var searchString = "" var body: some View { NavigationView { List { // 3. ForEach(searchString == "" ? countries: countries.filter { $0.contains(searchString)}, id: \.self) { country in Text(country) } .navigationTitle("Countries") } // 4. .searchable(text: $searchString) } } }
  1. A propery array of countries is declared.

  2. The searchstring holds the text entered inside the search bar.

  3. The regular countries will be displayed when the search bar is empty. When the user inserts the search string, the list is searched with that string and the results are displayed

  4. The searchable modifier displays the Search Bar and hold the searchString binding

Go to the Preview and select Live Preview. The countries list is displayed.

Enter The text to be searched inside the Search Bar and the results will be displayed.

swiftui-search-bar-search-results-preview.png

The source code of the SwiftUISearchBarTutorial can be downloaded at the ioscreator repository on Github.


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK