I add UISegmentedControl on storyboard and add SearchBar in code:
searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.delegate = self
searchController.searchBar.sizeToFit()
searchController.dimsBackgroundDuringPresentation = false
discountTableView.tableHeaderView = searchController.searchBar
Invalid position of Search Bar after its activation.
How fix it?
Before clicking,
After clicking
I overcame this by implementing delegate method of UISearchController
- (void)willPresentSearchController:(UISearchController *)searchController {
if (searchController.searchBar.scopeButtonTitles.count == 0) {
//somewhere I got this
// there is an Apple bug when first time configuring search bar scope buttons
// will be displayed no matter what with minimal searchbar
// to fix this adding scope buttons right before user activates search bar
searchController.searchBar.showsScopeBar = NO;
searchController.searchBar.scopeButtonTitles = #[#"title 1", #"title 2"];
}
}
Hope it will help you too.
Related
So I have a navigation controller hooked up to a view controller. That obviously provides the default navigation bar. Below that, I have another navigation bar with two buttons. In code I am manually adding the search bar that the UISearchController provides to that navigation bar. Below that, there is another filter view (custom), then a UITableView. Everything seems to work, but when I click search and start typing, the result view covers up the second navigation bar and the search bar, making it sort of useless. I tried playing around with self.searchController.hidesNavigationBarDuringPresentation = NO; but that just hides the main navigation bar. The even more infuriating part is the result view controller is actually leaving space for the second navigation bar, but it's just hidden behind this. It is even possible to see this in the debug view heirachy menu. Here’s the code I'm using for the search controller:
CUSearchResultsTableViewController *results = [self.storyboard instantiateViewControllerWithIdentifier:#"searchResults"];
self.searchController = [[UISearchController alloc] initWithSearchResultsController:results];
self.searchController.searchResultsUpdater = self;
self.searchBarNavItem.titleView = self.searchController.searchBar;
self.searchController.hidesNavigationBarDuringPresentation = NO;
self.searchController.obscuresBackgroundDuringPresentation = NO;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.definesPresentationContext = YES;
self.searchController.delegate = self;
self.searchController.searchBar.delegate = self;
Here is how you can do it:
objective-c
[self.navigationItem setHidesSearchBarWhenScrolling:NO];
Swift
self.navigationItem.hidesSearchBarWhenScrolling = false;
When setting a UISearchController search bar in the navigationItem titleView, the search bar can't be edited.
In my viewDidLoad I am configuring a UISearchController.
self.searchViewController = [self.storyboard instantiateViewControllerWithIdentifier:NSStringFromClass([SearchViewController class])];
self.searchViewController.delegate = self;
self.searchController = [[UISearchController alloc] initWithSearchResultsController:self.searchViewController];
self.searchController.delegate = self;
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.delegate = self;
self.navigationItem.titleView = self.searchController.searchBar;
I can't tap the search bar. The cursor does not appear and there is no user interaction.
Oddly, if I initialize the UISearchController locally without setting it to a property, then I can edit the search bar, just no delegate callbacks.
self.searchViewController = [self.storyboard instantiateViewControllerWithIdentifier:NSStringFromClass([SearchViewController class])];
self.searchViewController.delegate = self;
UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:self.searchViewController];
searchController.delegate = self;
searchController.searchResultsUpdater = self;
searchController.searchBar.delegate = self;
self.navigationItem.titleView = searchController.searchBar;
Another interesting behavior is that the clear button works (if some text is set in the search bar while initializing).
I had the same issue.
Imagine you have FirstViewController and SecondViewController, and booth have a UISearchBar on the titleView.
To fix the problem I had this code to booth UIViewController's.
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.definesPresentationContext = true
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.definesPresentationContext = false
}
I am setting self.definesPresentationContext = YES; in the view controller that presents the view controller in question.
This must be set to self.definesPresentationContext = NO; in viewWillAppear:.
Now the search bar in the presented view controller can be edited.
Set your search bar to navigation title view :
self.navigationItem.titleView = self.searchBarTop;
then just set this view either left/right button of Navigation Bar
UIBarButtonItem *searchBarItem = [[UIBarButtonItem alloc] initWithCustomView:searchBar];
self.navigationItem.rightBarButtonItem = searchBarItem;
I hope this will work for You!!
I have just solved a very similar problem in my app, and thought I'd share the solution in case the existing solutions don't fix it for you.
In my case I had a tab bar application, with my custom controllers in the tabs, embedded in the navigation controllers. The symptoms were exactly the same, the search bar showed in the title area of the navigation bar, but was not interactive.
I have discovered that the problem was that I used my custom subclass of the UITabBarController and I have overriden the viewWillAppear(animated:) method, but forgot to call super.viewWillAppear(animated:) in the implementation. The additional symptom was that when I switched the tabs, the search bar suddenly became interactive and everything worked fine, just the interaction on the initial tab was disabled.
I hope this helps someone.
In your first block of code, you're instantiating with a SearchViewController identifier. In the second, you're using HBSearchViewController. This suggests that there might be another difference in your code besides using / not using an outlet.
In my app, I need to create a Search Suggestions interface -- very similar to Google search (it starts displaying suggestions as you type in the search field).
I did it with a UISearchController with the search bar in navigation bar, set it up like this:
// setup search controller
searchController = UISearchController(searchResultsController: searchSuggestionsController)
self.searchController.searchResultsUpdater = searchSuggestionsController
self.searchController.hidesNavigationBarDuringPresentation = false
self.navigationItem.titleView = self.searchController.searchBar
// ISSUE!! definesPresentationContext needs to be false or I can't push this
// controller multiple times on the navigation stack
self.definesPresentationContext = true
while it works fine when search controller is pushed to the navigation stack the first time, it doesn't let the search bar get the focus when it is pushed the second time, as shown below
but if I set it to false: as soon as I start typing into the search bar, the navigation bar (along with the search bar) disappears. This is expected behavior since (because of definesPresentationContext = false) UISearchController is now trying to display its view on top of UINavigationController's view, as shown below:
Is there a way to achieve this through UISearchController? If not, any pointers on how should I create a custom control for this? (Code for the minimal app shown in the animations can be downloaded here)
It's not possible to use UISearchController like this. UISearchBar and UINavigationBar are known to not play well together. What I decided to do was, every time user taps the Search button, I check childViewControllers array of my navigation controller and if I find an instance of SearchViewController in there, I pop back to it. Otherwise I push it.
// This function lives inside a UINavigationController subclass and is called whenever I need to display the search controller
func search() {
if let _ = self.topViewController as? SearchViewController {
return
}
var existingSearchController: SearchViewController? = nil
for childController in self.childViewControllers {
if let searchController = childController as? SearchViewController {
existingSearchController = searchController
}
}
if let searchController = existingSearchController {
self.popToViewController(searchController, animated: true)
return
}
self.performSegueWithIdentifier(StoryboardConstants.SegueShowSearchController, sender: nil)
}
The proper fix would have been, of course, a custom control but we did not have the time to write something custom at this stage.
I have the following code in my app, specifically in viewDidLoad: that sets up my UISearchController.
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.hidesNavigationBarDuringPresentation = NO;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.definesPresentationContext = NO;
self.searchController.searchBar.scopeButtonTitles = #[];
self.searchController.searchBar.searchBarStyle = UISearchBarStyleProminent;
[_tableView setTableHeaderView:_searchController.searchBar];
Whenever the search bar (which is added to the tableView) is invoked, the UIStatusBar color changes from UIStatusBarStyleLightContent to dark (white to black). Now, I figured out if I set,
self.definesPresentationContext = NO;
to the following:
self.definesPresentationContext = YES;
the issue is solved and the UIStatusBar color is preserved. However, another issue arises. When self.definesPresentationContext is set to YES
, upon invocation the search bar shifts down for some reason, coincidently (or rightfully so) right under where the bottom of the UIRefreshControl displays on the tableView.
Setting View-controller based status bar appearance to No is not a solution if you want the view controllers to define how the status bar looks.
My solution consisted of two things:
Make sure the presenting view controller has definesPresentationContext set to YES
Make sure both the view controller that is pushed and the pushing view controller are laid out beneath the navigation bar (set extendedLayoutIncludesOpaqueBars to YES)
As of iOS 10 (maybe earlier?), if you have "View controller-based status bar appearance" set to YES in your Info.plist, simply set the preferredStatusBarStyle in the UIViewController that the UISearchController is included in.
- (UIStatusBarStyle)preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
(you don't need to subclass or create a category/extension of UISearchController to override preferredStatusBarStyle... it uses the preferredStatusBarStyle that you set in your UIViewController)
I needed full control over my status bar colour. I use the extensions found here to ensure that the visible view controller is setting the preferred status bar colour.
For me it was therefore necessary to override UISearchController and override preferredStatusBarStyle and return the style I wanted.
If you ViewController is inside a TabBarController then -
Instead of
self.definesPresentationContext = YES;
Use self.tabBarController.definesPresentationContext = YES;
This worked for me in above scenario.
The status bar that is displayed when the search controller is presented (is active) belongs to the search controller. To set the preferred status bar style you must add a category to UISearchController and then override the preferredStatusBarStyle method.
Below is an example of the implementation file of the category:
#implementation UISearchController (Customization)
-(UIStatusBarStyle)preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
#end
Or we can write an extension on Swift (version 2, but you can translate it to 3 easily):
extension UISearchController {
override public func preferredStatusBarStyle() -> UIStatusBarStyle{
if Theme.lightTheme() {
return UIStatusBarStyle.Default
}
else {
return UIStatusBarStyle.LightContent
}
}
}
Where Theme is a class that regulate app colour theme.
I'm looking to create similar functionality to Apple's maps application in Swift. Is there anyway to integrate a UISearchController in to a regular view (i.e.: not a UITableView). Dropping one in through Storyboard results in a crash after clicking inside the connected searchbar. Or is there some way I can achieve this outcome with a UITableView?
If you want to use UISearchController with a non UITableView, here is how I did it.
Since the UISearchController is not (yet!) supported by IB, you do not need to add anything in it, like a UISearchBar.
#interface UIViewControllerSubclass () <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating>
#property (strong, nonatomic) UISearchController *searchController;
#end
#implementation UIViewControllerSubclass
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any custom init from here...
// Create a UITableViewController to present search results since the actual view controller is not a subclass of UITableViewController in this case
UITableViewController *searchResultsController = [[UITableViewController alloc] init];
// Init UISearchController with the search results controller
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
// Link the search controller
self.searchController.searchResultsUpdater = self;
// This is obviously needed because the search bar will be contained in the navigation bar
self.searchController.hidesNavigationBarDuringPresentation = NO;
// Required (?) to set place a search bar in a navigation bar
self.searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
// This is where you set the search bar in the navigation bar, instead of using table view's header ...
self.navigationItem.titleView = self.searchController.searchBar;
// To ensure search results controller is presented in the current view controller
self.definesPresentationContext = YES;
// Setting delegates and other stuff
searchResultsController.tableView.dataSource = self;
searchResultsController.tableView.delegate = self;
self.searchController.delegate = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.searchBar.delegate = self;
}
#end
I hope it is enough to work :-)
Then of course you need at least to implement UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdater methods.
Enjoy!
Trying to figure out UISearchController myself. Setting it to the titleView is convenient, but on one of my pages, I had to put the searchBar near the top of the UIViewController:
// Add a normal View into the Storyboard.
// Set constraints:
// - height: 44
// - leading and trailing so that it spans the width of the page
// - vertical position can be anywhere based on your requirements, like near the top
#IBOutlet weak var searchContainerView: UIView!
var searchResultsController = UISearchController()
override func viewDidLoad() {
// TODO: set the searchResultsController to something
let controller = UISearchController(searchResultsController: nil)
// have the search bar span the width of the screen
controller.searchBar.sizeToFit()
// add search bar to empty View
searchContainerView.addSubview(controller.searchBar)
searchResultsController = controller
}
UPDATE:
After implementing UISearchController in a project or two, I found myself gravitating toward #adauguet's approach of embedding the search bar into the Navigation Bar.
Here's the code in Swift. One difference though is that it doesn't set the searchBar delegate, since searchResultsUpdater already listens for text changes.
override func viewDidLoad() {
super.viewDidLoad()
// locationManager.delegate = self
// locationManager.desiredAccuracy = kCLLocationAccuracyBest
// locationManager.requestWhenInUseAuthorization()
// locationManager.requestLocation()
let locationSearchTable = storyboard!.instantiateViewControllerWithIdentifier("LocationSearchTable") as! LocationSearchTable
resultSearchController = UISearchController(searchResultsController: locationSearchTable)
resultSearchController?.searchResultsUpdater = locationSearchTable
let searchBar = resultSearchController!.searchBar
searchBar.sizeToFit()
searchBar.placeholder = "Search for places"
navigationItem.titleView = resultSearchController?.searchBar
resultSearchController?.hidesNavigationBarDuringPresentation = false
resultSearchController?.dimsBackgroundDuringPresentation = true
definesPresentationContext = true
}
Also, I wrote a blog post that creates a project from scratch that uses UISearchController to display map search results. It also does other things that you might want in a map project, like get the user location, drop pins, parse placemarks into a one-line address, and create callout buttons that take you to Apple Maps for driving directions.
http://www.thorntech.com/2016/01/how-to-search-for-location-using-apples-mapkit/
The blog post is quite long, so here's the associated git repo if you just want to skip to the code:
https://github.com/ThornTechPublic/MapKitTutorial
I added a Search Bar and Search Display Controller in my View Controller in the storyboard. The view controller contains only the search bar and search display controller and does not have it's own TableView. When you add the search bar in your view controller, it sets your view controller as it's delegate automatically.
Now the Search Bar and Search Display Controller has a table view of itself which it uses to display the search results when you click inside the box and start typing. This table view expects your view controller to provide the implementations of the numberOfRowsInSection and cellForRowAtIndexPath functions for it to display the data properly.
When you run your project without these and tap inside the search bar, you will get the following error:-
tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0x7fbf63449660
*** Terminating app due to uncaught exception 'NSInvalidArgumentException'
If you see, the error is at the numberOfRowsInSection method.
Change your view controller definition from
class ViewController: UIViewController
to
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource
and implement the required methods which are:-
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return UITableViewCell()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
I have just added default return values in the above methods.
Now if you filter out your data source in your searchviewdelegate methods and set up your number of rows and cell info in the above two methods properly, it should work.
Hope this helps!
I had some trouble converting from SearchDisplayController in UIViewController to SearchController in ViewController because SearchController implementation isn't so intuitive. But you can just add in searcher from SearchController itself into any view. You cannot set constraint though because the search bar would move up when you focus/select it (if you know how to set the constraint to seachController.searchbar after adding it to any view, LET ME KNOW!). Below I am sharing a checklist that I found very important/valuable when implementing SearchController in ViewController.
//you can just add searcher to any view. It would automatically move up to show the tableView like magic. But for this reason, you cannot set constraint to the search bar to the placeholder view that you are adding it to.
[self.searchBarPlaceHolderView addSubview:self.searchController.searchBar];
//you need this to prevent search bar to drop down when you focus/select it. You would want to set this to NO if you are adding searchBar to the navigation bar's titleview.
self.searchController.hidesNavigationBarDuringPresentation = YES;
//make sure you set this in your viewController
self.extendedLayoutIncludesOpaqueBars = true;
self.definesPresentationContext = YES;
// you also need to give the search controller a tableViewController that can be displayed. You can also do just self.searchResultsController = [[UITableView alloc] init] for a generic one.
self.searchResultsController = (UITableViewController *)[ [UIStoryboard storyboardWithName:#"Main" bundle:nil] instantiateViewControllerWithIdentifier:#"searchResultsTableViewController"];
self.searchResultsController.tableView.dataSource = self;
self.searchResultsController.tableView.delegate = self;
self.searchResultsController.definesPresentationContext = NO;
self.searchController = [[UISearchController alloc] initWithSearchResultsController:self.searchResultsController];