Using a UISearchController with a UISearchBar in a HeaderView table in iOS11

Has anyone successfully saved UISearchBarto tableHeaderViewa UITableViewin ios11? Problems usually arise with the iPhone X in the landscape:

enter image description here

Apple recommends using the new property searchController:

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

However, this does not always work. Here is a code example:

iOS11 UISearchBar missing in UINavigationBar when embedded in UISplitViewController

Therefore, trying to save searchBarin tableHeaderView, the first practical step is to apply the appropriate layout restrictions:

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

Then displayed searchBarat the correct size:

enter image description here

However, the problem occurs when it is activated 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 . , .

?

+4

Source: https://habr.com/ru/post/1687456/


All Articles