UITableView with search – Swift iOS

In this tutorial, we are going to teach you, how you can create a UITableView with search bar in iOS using Swift 4. Following are the steps:

Video tutorial:

  1. Create a new project in XCode.
  2. Drag and drop a “Table view” in your storyboard.
  3. Open assistant from top menu bar Editor > Assistant.
  4. Hold shift and drag & drop your tableview in your controller to create an outlet. Give it a name like “tableview”.
@IBOutlet weak var tableview: UITableView!
  1. Connect datasource and delegate of your table view with your controller.
  2. Extend your view controller from UITableViewDataSource and UITableViewDelegate.
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
  1. Create an array of data, you might be getting this from API:
private var array: [String] = ["Cow", "Lion", "Wolf", "Camel", "Tiger"]
  1. Now register your table view with Swift built-in table view cell:
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    
    self.tableview.register(UITableViewCell.self, forCellReuseIdentifier: "cellIdentifier")
}
  1. Now create 3 functions:
    • 1st will return the total number of items needs to be displayed in table view.
    • 2nd will display the values from array in each table view cell.
    • 3rd will be called whenever any cell item is being tapped or clicked.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.array.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: UITableViewCell = self.tableview.dequeueReusableCell(withIdentifier: "cellIdentifier")!
    
    cell.textLabel?.text = self.array[indexPath.row]
    
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print(self.array[indexPath.row])
}
  1. Then drag and drop “Search bar” in your storyboard at the top of table view and create its outlet in your controller same as you did in step 4.
@IBOutlet weak var searchBar: UISearchBar!

At this point, you can see the UITableView with search on top in the XCode preview. But we need to make it functional.

  1. Join it’s delegate with your controller same as in step 5.
  2. Implement the UISearchBarDelegate in your controller class:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
  1. Create another array which will hold the initial values:
private var initialArray: [String] = ["Cow", "Lion", "Wolf", "Camel", "Tiger"]
  1. Finally, create a function which will be called whenever you type something in the search bar. This function search the text in all the initial values of array. You can make the search case insensitive by making both the text lowercased, text of search bar and of array. We also have to put a condition that when the search bar is empty, then we will display all the values from initial array. Lastly, you need to reload the data in table view in order to see searched data.
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    let text: String = self.searchBar.text ?? ""
    self.array = []
    for item in self.initialArray {
        if (item.lowercased().contains(text.lowercased())) {
            self.array.append(item)
        }
    }
    if (text.isEmpty) {
        self.array = self.initialArray
    }
    self.tableview.reloadData()
}

Follow more iOS tutorials.

[wpdm_package id=’727′]