Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 700
Zayin Krige Avatar asked Oct 03 '13 14:10

Zayin Krige


2 Answers

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;
}
like image 146
Zayin Krige Avatar answered Oct 11 '22 19:10

Zayin Krige


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.

like image 28
c0deslayer Avatar answered Oct 11 '22 17:10

c0deslayer