键盘隐藏后,UISearchDisplayController tableview内容偏移量不正确

Zay*_*ige 8 objective-c uitableview uisearchdisplaycontroller ios

我有一个UISearchDisplayController,它在tableview中显示结果.当我尝试滚动tableview时,contentsize正好是_keyboardHeight比它应该更高.这导致错误的底部偏移.tableview中有大于50个项目,因此下面不应有空格

在此输入图像描述

Zay*_*ige 12

我通过添加一个NSNotificationCenter监听器解决了这个问题

- (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];
}
Run Code Online (Sandbox Code Playgroud)

别忘了删除监听器

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

在通知方法中调整tableview内容

- (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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这[答案](http://stackoverflow.com/a/19162257/467588)类似但有点短;) (2认同)

小智 12

基于Hlung发布的链接,这是一种更简单方便的方法:

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

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

}
Run Code Online (Sandbox Code Playgroud)

注意:原始答案使用NSNotificationCenter生成相同的结果.