Search code examples
iphoneiosuitableviewuisearchdisplaycontroller

How can I add a UISearchDisplay controller PROGRAMMATICALLY?


I've been searching for this day, but I can't find it....

Could anyone point me to a tutorial/tell me what I should do? The documentation wasn't really helpful... I need this for my UITableViewController class (without a xib!)

Thanks A lot!


Solution

  • First do Gray UISearchBar w/matching scope bar programmatically

    Then since the tableview and the searchtableview both use the same datasource, you have to insert an if statement in the tableview delegate methods like this:

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        if (tableView == self.searchDisplayController.searchResutsTableView) {
            tableViewData = searchResultsData objectatindex...; //array with filtered data
        } else {
            tableViewData = defaultData objectatindex...; //array with unfiltered data
        }
    }
    

    Do the same for the number of rows delegate method:

    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        if (tableView == self.searchDisplayController.searchResultsTableView) {
            return searchResultsData.count;
        } else {
            return defaultData.count;
        }
    }
    

    Then after the search text changes or search button is pressed (look at UISearchBar delegate methods), reload data to display.