【问题标题】:UISearchDisplayController tableview content offset is incorrect after keyboard hide键盘隐藏后 UISearchDisplayController 表格视图内容偏移不正确
【发布时间】:2014-07-30 10:30:12
【问题描述】:

我有一个 UISearchDisplayController,它在表格视图中显示结果。当我尝试滚动表格视图时,内容大小正好 _keyboardHeight 比它应该的高。这导致假底部偏移。 tableview 中有 > 50 个项目,所以下面不应该有空格

【问题讨论】:

    标签: ios objective-c uitableview uisearchdisplaycontroller


    【解决方案1】:

    我通过添加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];
    }
    

    别忘了移除监听器

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

    调整通知方法中的tableview contentsize

    - (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;
    }
    

    【讨论】:

    • 这个answer 类似,但短一点;)
    【解决方案2】:

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

    - (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView {
    
         [tableView setContentInset:UIEdgeInsetsZero];
         [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
    
    }
    

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

    【讨论】:

      猜你喜欢
      • 2014-07-18
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      相关资源
      最近更新 更多