Search code examples
iosobjective-cswiftuitableviewuisearchcontroller

How to show "No results found" in UITableView, if there is no search result returned?


In a table view, i am showing "No results found" if no results returned by search controller by adding an else condition as below-

In numberOfRowsInSection:

else if self.searchController.active && self.searchController.searchBar.text?.characters.count > 0 &&
        self.filteredLanguages.count == 0 {
        return 1
}

In cellForRowAtIndexPath:

else if self.searchController.active && self.searchController.searchBar.text?.characters.count > 0 &&
        self.filteredLanguages.count == 0 {
        cell.textLabel?.text = "No results found"
        cellImage = nil
        cell.userInteractionEnabled = false
        isNoResultCell = true
}

if filteredIndexPath!.row == userSettings.valueForKey("selectedRow") as? Int  && !isNoResultCell {
        cell.tintColor = UIColor.whiteColor()
        cell.accessoryType = UITableViewCellAccessoryType.Checkmark
        lastSelectedRow = filteredIndexPath
}

I did some research about approaches to show "No results found" in table view but that after writing above logic.

And as per few posts, i can add a UILabel as sub view in background view of table in numberOfSectionsInTableView when there are no search results and remove the subview if search results are returned.

My question is - Which is the most resource/performance savvy option ?


Solution

  • You need to take a UILabel that will be hidden when your tableview have records (i.e. array having records that is going to be shown in tableview).

    When you search a record and you get no records the you can hide tableview and show label having text "No results found".