Search code examples
xcodeuitableviewmaster-detailsections

Section Titles messed up when using search bar + detail view


I'm building my first app an am stuck. My section titles are showing up improperly.

  • I have a master table view with a search bar to filter my items.
  • I have sections in my table view
  • I have a segue to a detail view to show more details on the tapped item.

Everything works fine. I can filter my items in the master view using the search bar. Sections still show correctly on the search results. I can also tap on one of the items in the filtered search results. The Detail TableView appears to show more details. Fine.

When I return to my Master tableView from the detail view the filtered items appear under their sections. BUT - the original section titles ALSO appear (overlapped) as if all (unfiltered) items were listed.

I found that right before I display the detail Table View the Master View's

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String {
    if tableView == self.searchDisplayController!.searchResultsTableView {
        println("COOL")
    } else {
        println("Damn, it doesn't recognize that its filtered.")   
    }

    ...
}

function triggers and believes that its "tableView" is no longer filtered.

The app works perfectly if I don't filter and tap on items and then return to Master View.

Does anybody have any ideas what I might be doing incorrectly?

Thanks, Daniel


Solution

  • This solves the problem. The "self.tableView.reloadData()" was causing this behaviour:

    override func viewWillAppear(animated: Bool) {
        // DO NOT UNCOMMENT THIS!!! IT BREAKS THE SEARCHING - WHEN I SEARCH AND 
        // THEN CLICK ON AN ITEM AND GO TO THE DETAIL VIEW CONTROLLER AND THEN GO 
        // BACK TO THE MAIN VIEW CONTROLLER THEN THE ORIGINAL SECTION HEADERS 
        // APPEAR ON TOP OF THE RESULTS VIEW.
        // self.tableView.reloadData()
    
        super.viewWillAppear(animated)
    }