How to fix iOS 11 search bar jumping to top of screen on select (Swift)?

Viewed 1934

Specifically, with iOS 11 (and not previous OS), when you tap a search bar to start typing, it jumps to the top of the screen.

I can fix this when the search bar is already near the top of the screen by using this code:

if #available(iOS 11, *) {
     navigationItem.searchController = searchController

     navigationItem.hidesSearchBarWhenScrolling = false
} else {
     BugsTable.tableHeaderView = searchController.searchBar
}

But, when I have a search bar in the middle of a view (i.e some other element is above it), that code won't work as it is telling the search bar inside the navigation controller. I saw the following questions, but no working answer for Swift:

iOS 11 search bar jumping to top of screen

iOS 11 Searchcontroller jumps top of screen

My ViewDidLoad setup parameters are:

searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.sizeToFit()
ResultsTable.tableHeaderView = searchController.searchBar
searchController.searchBar.barTintColor = MyGlobalVariable.themeMainColor

What am I missing here?

1 Answers

try this:

   if (@available(iOS 11, *)){

            [searchVC.searchBar addObserver:self forKeyPath:@"frame" options: NSKeyValueObservingOptionNew context:nil];

        }else{

            [view addSubview:searchVC.searchBar];
        }

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{

        CGRect rect = [change[@"new"] CGRectValue];
        if (rect.origin.y == 14) {
            CGRect temp = rect;
            temp.origin.y = 20;
            [self.searchVC.searchBar setValue:@(temp) forKey:@"frame"];
        }else if (rect.size.height == 56){

            CGRect temp = rect;
            temp.size.height = 50;
            [self.searchVC.searchBar setValue:@(temp) forKey:@"frame"];
        }
    }
Related