Accessing index path row after search

951 views Asked by At

I populate a table with data and all works as intended - including segueing each row's details to another scene. I throw a search bar in there (programmatically - using the new searchController) and it successfully reloads the original table with any found results.

HOWEVER, when touching a selected row after a search, the segue passed along is that of the original table row that happens to be in the same position of the one touched now! (i.e. if I choose the current second row of a search, the next scene will segue the details of the second row of the original table!)

So how do I provide the prepareForSegue function my correct row after a search?

This is the cell creation:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

    if (self.resultSearchController.active) {
        cell.textLabel?.text = filteredTableData[indexPath.row]

        return cell
         }
    else {

    cell.textLabel?.text = TableTitle[indexPath.row]

return cell
}
}

And this is the search function:

func updateSearchResultsForSearchController(searchController: UISearchController)
{
    filteredTableData.removeAll(keepCapacity: false)

    let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text)
    let array = (the_tableData as NSArray).filteredArrayUsingPredicate(searchPredicate)
    filteredTableData = array as! [String]

    self.tableView.reloadData()
}

and this is the segue:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using [segue destinationViewController].

    var thirdScene = segue.destinationViewController as! customer_details_View_Controller
    if let indexPath = self.tableView.indexPathForSelectedRow() {

        thirdScene.basics = the_basics[indexPath.row]
        thirdScene.p_method = the_p_method[indexPath.row]
        thirdScene.notes = the_notes[indexPath.row]

    }

    // Pass the selected object to the new view controller.
}
1

There are 1 answers

1
CalZone On BEST ANSWER

You have to check for search result active in prepareFOrSegue or DidSelectRowAtIndexPath as well.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].

var thirdScene = segue.destinationViewController as! customer_details_View_Controller

if self.resultSearchController.active && searchController.searchBar.text != "" {
// Select data from Filtered Array
} else {
 // Select data from regular array
}
}

Rey Wenderlich has an excellent tutorial for this:

https://www.raywenderlich.com/113772/uisearchcontroller-tutorial