iOS programmatically added UITableView and UISearchDisplayController

219 views Asked by At

I have a UIViewController into which I want to add a UITableView and a UISearchBar. The UISearchBar should not be added to the tableView but stay just above the tableView.

I came up with this implementation for the containing viewController:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.testTableView = [[TestTableViewController alloc] init];
    self.testTableView.edgesForExtendedLayout = UIRectEdgeNone;

    self.searchBar = [[UISearchBar alloc] init];
    self.searchBar.delegate = self.testTableView;

    self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self.testTableView];
    self.searchController.delegate = self.testTableView;
    self.searchController.searchResultsDataSource = self.testTableView;
    self.searchController.searchResultsDelegate = self.testTableView;

    self.searchBar.frame = CGRectMake(500.0f, 70.0f-44.0f, 500.0f, 44.0f);
    self.testTableView.view.frame = CGRectMake(500.0f, 70.0f, 500.0f, 500.0f);

    // add views
    [self.view addSubview:self.testTableView.view];
    [self.view addSubview:self.searchBar];
}

TestTableViewController is basically a common TableViewController with some dummy data.

This seems to work fine but when I do a search it seems that the searchResults tableView is added to the original tableView and I end up with strange artefacts which arise when you have a scroll view inside a scroll view.

I made the observation that I don't have this problem if I add the searchBar to the tableView like that:

self.testTableView.tableView.tableHeaderView = self.searchBar;

instead of:

[self.view addSubview:self.searchBar];

But this results in other problems (line just above the searchBar, the searchBar scrolls with content).

Also: - I can't use the new UISearchController - I can't use story board to implement this

Does anyone have an idea what may be wrong here? Maybe there's a problem in the code above.

You can download the example project here: http://www.file-upload.net/download-9987146/SearchTableViewTest.zip.html

0

There are 0 answers