Search code examples
iosuisearchbaruisearchcontrollerios11xcode9

UISearchBar at wrong position in iOS 11


Adopting our code to iOS 11, i am struggling with the UISearchbar positioned in the UINavigationController. I set up the SearchController/SearchBar like this:

self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchBar.scopeButtonTitles = @[@"foo", @"bar"];
self.searchController.searchBar.showsScopeBar = YES;
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.delegate = self;
self.searchController.delegate = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.hidesNavigationBarDuringPresentation = NO;
self.definesPresentationContext = YES;
if (@available(iOS 11.0, *))
{
    self.navigationItem.searchController = self.searchController;
    self.navigationItem.hidesSearchBarWhenScrolling = YES;
    UISearchBar *searchbar = self.searchController.searchBar;
    [searchbar setSomeColors];
}

When using our default colors, things might look OK, but the space between SearchBar and ScopeButtons might be a bit too big: default layout Changing the backgroundColor of the searchbar reveals what is going wrong: different coloring reveals the problem

So, the UISearchBar is placed a bit too high in its superview. Does anyone know, what causes this behaviour in iOS 11?


Solution

  • Whoa, i had no idea, this existed since iOS 5…

    [self.searchController.searchBar setSearchFieldBackgroundPositionAdjustment:UIOffsetMake(0.0, 8.0)];
    

    See UISearchBar.h

    @property(nonatomic) UIOffset searchFieldBackgroundPositionAdjustment NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;