Zayin Krige
Zayin Krige

Reputation: 3308

UISearchDisplayController tableview content offset is incorrect after keyboard hide

I've got a UISearchDisplayController and it displays results in a tableview. When I try scroll the tableview, the contentsize is exactly _keyboardHeight taller than it should be. This results in a false bottom offset. There are > 50 items in the tableview, so there shouldn't be a blank space as below

enter image description here

Upvotes: 8

Views: 5828

Answers (2)

c0deslayer
c0deslayer

Reputation: 545

Here is a more simple and convenient way to do it based on Hlung's posted link:

- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView {

     [tableView setContentInset:UIEdgeInsetsZero];
     [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];

}

Note: The original answer uses NSNotificationCenter to produce the same results.

Upvotes: 12

Zayin Krige
Zayin Krige

Reputation: 3308

I solved this by adding a NSNotificationCenter listener

- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView {
    //this is to handle strange tableview scroll offsets when scrolling the search results
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidHide:)
                                                 name:UIKeyboardDidHideNotification
                                               object:nil];
}

Dont forget to remove the listener

- (void)searchDisplayController:(UISearchDisplayController *)controller willHideSearchResultsTableView:(UITableView *)tableView {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardDidHideNotification
                                                  object:nil];
}

Adjust the tableview contentsize in the notification method

- (void)keyboardDidHide:(NSNotification *)notification {
    if (!self.searchDisplayController.active) {
        return;
    }
    NSDictionary *info = [notification userInfo];
    NSValue *avalue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize KeyboardSize = [avalue CGRectValue].size;
    CGFloat _keyboardHeight;
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (UIDeviceOrientationIsLandscape(orientation)) {
        _keyboardHeight = KeyboardSize.width;
    }
    else {
        _keyboardHeight = KeyboardSize.height;
    }
    UITableView *tv = self.searchDisplayController.searchResultsTableView;
    CGSize s = tv.contentSize;
    s.height -= _keyboardHeight;
    tv.contentSize = s;
}

Upvotes: 12

Related Questions