在iOS11中的tableHeaderView中使用UISearchController和UISearchBar

时间:2017-10-13 19:51:51

标签: ios uitableview uisearchbar ios11 uisearchcontroller

是否有人在ios11的UISearchBar tableHeaderView中成功保留了UITableView? iPhone X在景观中通常会出现问题:

enter image description here

Apple建议使用新的searchController属性:

if (@available(iOS 11.0, *)) {
    self.navigationItem.searchController = self.searchController;
    self.navigationItem.hidesSearchBarWhenScrolling = NO;
} else {
    self.tableView.tableHeaderView = self.searchController.searchBar;
}

然而,这并不总是有效。以下是代码示例:

iOS11 UISearchBar missing in UINavigationBar when embedded in UISplitViewController

因此,尝试将searchBar保留在tableHeaderView中 - 实际的第一步是应用适当的自动布局约束:

if (@available(iOS 11.0, *)) {
    UILayoutGuide *guide = self.tableView.safeAreaLayoutGuide;
    searchBar.translatesAutoresizingMaskIntoConstraints = NO;
    [searchBar.leftAnchor constraintEqualToAnchor:guide.leftAnchor].active = YES;
    [searchBar.rightAnchor constraintEqualToAnchor:guide.rightAnchor].active = YES;
}

显示时searchBar的大小正确:

enter image description here

然而,当UISearchBar被激活时会出现问题:

enter image description here

这似乎是一个老问题。有许多stackoverflow问题和答案与这样的问题有关。在这种情况下,在检查视图层次结构时,似乎UISearchBar的宽度设置不正确。所以这可以纠正:

- (void)didPresentSearchController:(UISearchController *)searchController NS_AVAILABLE_IOS(11_0)
{
    if (@available(iOS 11.0, *)) {
        CGRect frame = self.searchController.searchBar.frame;
        frame.size.width = [self safeWidthAvailable];
        self.searchController.searchBar.frame = frame;
    }
}

- (CGFloat)safeWidthAvailable
{
    CGRect frame = ((AppDelegate *)MyApplication.sharedApplication.delegate).window.frame;
    CGFloat width = frame.size.width;
     if (@available(iOS 11.0, *)) {
       UIEdgeInsets insets = ((AppDelegate *)MyApplication.sharedApplication.delegate).window.safeAreaInsets;
       width -= insets.left;
       width -= insets.right;
    }
    return width;
}

这样可行:

enter image description here

在您使用UISearchController有效时旋转:

enter image description here

再次UISearchController错位UISearchBar

为什么这么难?

一种解决方案是保存搜索,在旋转后禁用UISearchController,然后使用保存的搜索重新启用它。这有效,但不应该这么复杂。

有什么建议吗?

0 个答案:

没有答案