UISearchController 'Search Bar' width issue

We have developed an application for iOS 5 long back where we used 'Search Bar and Search Display Controller' object on storyboard. Since iOS8 UISearchDisplayController is deprecated, I am trying to remove existing 'Search Bar and Search Display Controller' with UISearchController.

As UISearchController is not available from 'Object Library' on interface, I have added it programatically to an UIView on interface using following code:

//Set up Search Controller
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = (id)self;
self.searchController.dimsBackgroundDuringPresentation = YES;
self.searchController.searchBar.delegate = self;
 
//Adding as subview to UIView 'searchBarContainer'
[self.searchBarContainer addSubview:self.searchController.searchBar];
[self.searchBarContainer bringSubviewToFront:self.searchController.searchBar];

self.definesPresentationContext = YES;
self.extendedLayoutIncludesOpaqueBars = YES;


And set the frame of 'searchController' equal to the UIView as follows:

UISearchBar *ctrlSearchBar = self.searchController.searchBar;
ctrlSearchBar.frame = CGRectMake(0, 0, self.searchBarContainer.frame.size.width, self.searchBarContainer.frame.size.height);


The size of searchBar is fine but when it is focused on clicking on it, the width of 'searchBar' increased automatically.

I even tried using NSLayoutConstraints but didn't fix the issue. Can anyone please help how to fix the size of 'UISearchController.searchBar' even when it is focused?

Accepted Reply

I found a workaround as suggested here.

I have created a custom UIViewController with UISearchController in it. I added it as child view controller in to my main UIViewController and the search bar didn't exceed the custom UIViewController's view width.

Replies

You have in IB a search Bar and Search Display controller.


Doesn't that suit your need ?


See tutorial here:

h ttps://www.hackingwithswift.com/example-code/uikit/how-to-use-uisearchcontroller-to-let-users-enter-search-words

'Search Bar and Search Display Controller' is associated with UISearchDisplayController which is deprecated since iOS8. I am working on replacing UISearchDisplayController with UISearchController.

So I can't use 'Search Bar and Search Display Controller'

I found a workaround as suggested here.

I have created a custom UIViewController with UISearchController in it. I added it as child view controller in to my main UIViewController and the search bar didn't exceed the custom UIViewController's view width.