Navigation Controller from Storyboard inherit from root controller (iOS11) - ios

In my app, I have a navigation controller (N1), controlling a tableview controller (T1) with a search bar.
When the search bar becomes active, a new navigation controller (N2) is presented from the storyboard to display the search results. (see image)
This worked perfectly fine, until iOS 11, where the search bar is moved from the tableview header to the navigation bar.
A partial solution is to differentiate between OS versions, as follows:
-(void)initSearchController{
UINavigationController *searchResultsController = [[self storyboard] instantiateViewControllerWithIdentifier:#"TableSearchResultsNavController"];
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
self.searchController.searchResultsUpdater = self;
self.searchController.hidesNavigationBarDuringPresentation = NO;
if (#available(iOS 11.0, *)) {
self.navigationItem.searchController = self.searchController;
//searchResultsController.navigationItem.searchController = self.searchController;
} else {
self.tableView.tableHeaderView = self.searchController.searchBar;
}
}
However, because of the new position of the search bar in iOS 11, as soon as the search results are displayed, the search box disappears, since it is part of the navigation bar that has been replaced by the alien storyboard navcontroller.
I also modified a method, that is called when the search bar becomes active, as follows, but still the search bar disappears:
// Called when the search bar becomes first responder
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
NSString *searchString = self.searchController.searchBar.text;
[self updateFilteredContentForSearchString:searchString];
if (self.searchController.searchResultsController) {
UINavigationController *navController = (UINavigationController *)self.searchController.searchResultsController;
SearchResultsTableViewController *vc = (SearchResultsTableViewController *)navController.topViewController;
self.searchController.dimsBackgroundDuringPresentation = false;
//my attempt, to no avail
if (#available(iOS 11.0, *)) {
vc.navigationItem.searchController = self.searchController;
} else {
vc.searchController=self.searchController;
}
vc.searchResults = self.searchResults;
[vc.tv reloadData];
}
}
What would be the approach to solve this? I want the app to remain compatible with pre-11 OS's (at least iOS10).
Do I have to completely rework this mechanism (if yes, how?), or is there just a simple line of code that would simply tell the controller N2 to also display the search bar?
Thanks for your insights

Related

iOS 11 show searchBar in navigation bar next to leftBarButtonItem

I am trying to get the new iOS-11 searchBar approach to work, but don't manage. The searchBar shows up, but is shown below the left bar button, instead of next to it:
It is the same in landscape mode.
The code that I am using is:
self.searchResults = [[SearchResultsTable alloc] init];
self.searchResults.delegate = self;
searchController = [[UISearchController alloc] initWithSearchResultsController:self.searchResults];
searchController.searchResultsUpdater = self.searchResults;
searchController.hidesNavigationBarDuringPresentation = NO;
self.definesPresentationContext = YES;
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(swapToListView:)];
if ([self.navigationItem respondsToSelector:#selector(setSearchController:)]) {
// only available from IOS-11 onwards
self.navigationItem.title = nil;
self.navigationItem.titleView = nil;
[self.navigationItem setSearchController:searchController];
} else {
// Fallback on earlier versions
self.navigationItem.titleView = searchController.searchBar;
}
The old code works fine on pre-iOS-11 systems, but has other problems on iOS-11, so I prefer to use the new approach.
Anybody knows what I am doing wrong here?
If you want to put search bar next to left navigation item then make your search bar navigationItem's titleView regardless of iOS version, and don't use UINavigationItem's searchController property.

UISearchBar animates incorrectly underneath the navigationBar

I have two view controllers each one contains UISearchController and a UITableView. The Code in viewDidLoad is:
SearchResultsTableViewController *searchResultController = [[SearchResultsTableViewController alloc]initWithNibName:#"SearchResultsTableViewController" bundle:nil];
UINavigationController *navSearchResultsController = [[UINavigationController alloc] initWithRootViewController:searchResultController];
self.searchController = [[UISearchController alloc] initWithSearchResultsController:navSearchResultsController];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = YES;
[self.searchController.searchBar sizeToFit];
self.searchController.searchBar.delegate = self;
self.searchController.delegate = self;
self.tableView.tableHeaderView = self.searchController.searchBar;
self.tableView.userInteractionEnabled = YES;
The first view controller is the rootViewController, which works perfectly without any problem. The second view controller is being pushed via the navigation controller based on segment selection.
[self.navigationController pushViewController:self.vc];
There is only one problem with the second view controller. When I tap on the searchBar, it animates to the top and goes underneath the navigation bar while the first one animates in its spot and does not go up.
Can anyone tell me how to disable this animation?
I want to keep the searchBar in its same place while searching. It's exactly the same implementation for both view controllers. Why does each one act differently?
Thanks,
Set the hidesNavigationBarDuringPresentation boolean on the UISearchController to NO.
self.searchController.hidesNavigationBarDuringPresentation = NO;
Or try this answer, it sounds similar to what you are trying to do. But you would probably want to adjust this line:
[super setActive: visible animated: animated]; // instead of passing animated, pass NO

Unwinding to view with search results controller active leaves black gap at top

I have multiple view controllers which all use one class (we'll call it searchClass <NSObject>) I wrote that has a UISearchController for searching an external API. The user can tap the search icon and the search controller becomes active: [_searchClass.searchController setActive:YES]; It uses its own table view controller (not the one in each of the view controllers, because they aren't all table view controllers).
In my case I make the search bar appear in the navigation bar. Search works great, the user can select a search result and tap it for a detail view. The problem is when the user goes back (unwinds) from the detail view to the search results, there is a black gap about 44 pts tall that appears briefly above the table view and below the navigation bar, and then disappears.
Here is my setup. In the view controller:
self.definesPresentationContext = YES;
_searchClass = [SearchClass new];
_searchClass.navController = [self navigationController];
In the search class:
_searchTableViewController = [[UIStoryboard storyboardWithName:#"MainStoryboard" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:#"searchTableViewController"];
_searchTableViewController.tableView.delegate = self;
_searchTableViewController.tableView.dataSource = self;
_searchTableViewController.tableView.backgroundColor = [UIColor clearColor];
_searchTableViewController.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
_searchTableViewController.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
_searchTableViewController.definesPresentationContext = YES;
_searchController = [[UISearchController alloc] initWithSearchResultsController:_searchTableViewController];
_searchController.delegate = self;
_searchController.hidesNavigationBarDuringPresentation = NO;
_searchController.searchBar.delegate = self;
_searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
_searchController.searchBar.showsCancelButton = YES;
_searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
There are also the usual delegate methods for UISearchBar and UISearchController, and the code that displays the search bar, which uses an animation to replace the titleView of the navigation bar.
How do I get rid of that gap after unwinding back to the search results?
I found the solution, it's related to the UINavigationBar. For some reason setting the translucent property to NO seems to have caused this issue.
self.navigationBar.translucent = YES;
Setting it to YES (or omitting the line since it is the default) made it work properly. Since I still wanted to have the navigation bar be opaque, I did the following to make the nav bar translucent only during transitions, which seems to be where the issue lies:
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
self.navigationController.navigationBar.translucent = YES;
}
-(void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
self.navigationController.navigationBar.translucent = NO;
}
Definitely seems like a genuine iOS bug to me.

Nothing happens when I click UISearchBar in NavigationBar

I added a UISearchBar to my initial UIViewController and everything works fine. However when I go to add the same UISearchBar, the same way to another ViewController that's pushed ontop of the first one, nothing seems to happen when I click into the searchBar. No delegate method is fired, no keyboard comes up, nothing.
This is how I'm adding it to the navigationBar:
- (void)viewDidLoad {
[super viewDidLoad];
UITableViewController *searchResultsController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
searchResultsController.tableView.dataSource = self;
searchResultsController.tableView.delegate = self;
self.searchResults = [NSMutableArray array];
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
self.searchController.searchResultsUpdater = self;
self.searchController.hidesNavigationBarDuringPresentation = NO;
self.searchController.searchBar.placeholder = NSLocalizedString(#"Search, eh?", nil);
// Include the search bar within the navigation bar.
self.navigationItem.titleView = self.searchController.searchBar;
self.definesPresentationContext = YES;
}
Like I said it works in the first UIViewController, am I missing something in the other 2-3 viewControllers I've tried adding this too? I don't see why the searchBar shows up in the navBar but nothing is happening upon clicking into it. I've also set the delegate like so:
#interface ViewController () <UISearchResultsUpdating>
Try setting definesPresentationContext to NO on the first view controller as soon as you present a new one on.
I believe that the presentation walks up the view controller hierarchy looking for the first one that defines a context and not down.

On iOS 7, pushing a controller with a toolbar leaves a gap of unusable space if it's ultimately contained within a tab bar controller

In my iOS app, my window's rootViewController is a tab bar controller with the a hierarchy like this:
UITabBarController
UINavigationController 1
FirstContentController
UINavigationController 2
...
UINavigationController 3
...
...
When the user taps a certain row on FirstContentController, an instance of SecondController will be pushed onto its navigation controller. SecondContentController sets hidesBottomBarWhenPushed to YES in its init method and sets self.navigationController.toolbarHidden to NO in viewWillAppear:.
In iOS 6, the user would tap the row in FirstController and SecondController would get pushed onto the nav controller. Because it has hidesBottomBarWhenPushed set, it would hide the tab bar and, by the time the transition animation was complete, SecondController would be on the screen with its toolbar visible.
However, when testing this under iOS 7, hidesBottomBarWhenPushed's behavior seems to have changed. What I see now is:
the tab bar hides, as expected
the toolbar appears, as expected
a gap of unusable space exactly 49 pixels tall (the height of the tab bar) appears between the toolbar and the content view
The gap is completely unusable - it doesn't respond to touches and if i set clipsToBounds to YES on the main view, nothing draws there. After a lot of debugging and examining subview hierarchies, it looks like iOS's autosizing mechanism resizes the view controller's view to a height of 411 (on the iPhone 5). It should be 460 to reach all the way down to the toolbar, but the layout system seems to be including a "ghost" 49-pixel-tall tab bar.
This problem only occurs if the view controller has a tab bar controller as one if its parent containers.
On iOS 7, how can I have the tab bar disappear and a toolbar seamlessly slide into place when a new controller is pushed, and still have the view take up the entire space between the navigation item and the toolbar?
UPDATE
After further investigation, this only happens if SecondController's edgesForExtendedLayout is set to UIRectEdgeNone. However, unless I set that property to UIRectEdgeNone, the view's frame is too long and extends under the toolbar, where it can't be seen or interacted with.
I found that adding the following 2 lines of code in viewDidLoad of SecondViewController (where you want to hide TabBar but show the tool bar) fixes the problem.
self.extendedLayoutIncludesOpaqueBars = YES;
self.edgesForExtendedLayout = UIRectEdgeBottom;
My viewDidLoad of SecondViewController is as follows:
- (void)viewDidLoad {
[super viewDidLoad];
// These 2 lines made the difference
self.extendedLayoutIncludesOpaqueBars = YES;
self.edgesForExtendedLayout = UIRectEdgeBottom;
// The usual configuration
self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
self.navigationController.navigationBar.translucent = NO;
self.navigationController.toolbarHidden = NO;
self.navigationController.toolbar.barStyle = UIBarStyleBlack;
self.navigationController.toolbar.translucent = NO;
.
.
}
But you need to fix the frame of the view manually as this causes the size to be (320x504). Which means it extends even behind the tool bar. If this is not a concern for you then this solution should work.
You will not like this answer This is not the answer you want, but after some research on hiding the tab bar in iOS7, my conclusion is: don't!
Tab bars have never been meant to be hidden - after all why have a UITabBarController if you want to hide the tab bar. The hidesBottomBarWhenPushed on view controllers is for hiding the bottom bar of a navigation controller, not tab bars. From the documentation:
A view controller added as a child of a navigation controller can display an optional toolbar at the bottom of the screen. The value of this property on the topmost view controller determines whether the toolbar is visible. If the value of this property is YES, the toolbar is hidden. If the value of this property is NO, the bar is visible.
Moreover, you are warned not to modify the tab bar object directly. Again, from the documentation:
You should never attempt to manipulate the UITabBar object itself stored in this property.
This is exactly what you are doing when setting it to hidden.
In iOS6 this has worked, but now in iOS7, it doesn't. And it seems very error prone to hide it. When you finally manage to hide it, if the app goes to the background and returns, Apple's layout logic overrides your changes.
My suggestion is to display your data modally. In iOS7 you can create custom transitions, so if it is important to you to have a push transition, you can recreate it yourself, although this is a bit over the top. Normal modal transition is something users are familiar, and actually fits this case better than push which hides the tab bar.
Another solution is to use a toolbar instead of a tab bar. If you use the navigation controller's toolbar for your tabs, you can then use hidesBottomBarWhenPushed as you require and it would give you the behavior you expect.
Uncheck "Hide bottoms bars on push" and set your autoconstraints as if there is a tab bar. Then in "ViewDidLoad" of the controller you want to hide the system tab bar, put the following code.
[self.tabBarController.tabBar setFrame:CGRectZero];
This makes sure the tab bar still accepts user interaction yet not visible to users. (other alternatives such as setting it 0 alpha or hidden will render tab bar useless) Now the autoconstaraints will make sure your view displays correctly with the tab bar height as zero.
It's a bug in iOS 7 UIKit due to this particular combination of:
UITabBarController
hidesBottomBarWhenPushed = YES
edgesForExtendedLayout = UIRectEdgeNone
UINavigationController toolbar
You should file a bug with Apple and include your sample code.
To work around the bug you need to remove one of those four conditions. Two likely options:
Fix the layout of your "second" view controller so that it works correctly when edgesForExtendedLayout is set to UIRectEdgeAll. This could be as simple as setting the contentInset on a scroll view.
Don't use UINavigationController's built-in toolbar. Instead, create a separate UIToolBar instance and manually add it to your second view controller's view.
You do have to set the tabBar of the TabBarController to hidden and your view should have autosizing set to flexible height.
With this code it's working:
#implementation SecondController
-(id)init
{
if( (self = [super init]) )
{
}
return self;
}
- (void)viewDidLoad;
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight;
self.tabBarController.tabBar.hidden = YES;
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// will log a height of 411, instead of the desired 460
NSLog(#"frame: %#", NSStringFromCGRect(self.view.frame));
}
#end
Or, if you do want to use the hidesBottomBarWhenPushed method, you have to do this before you push the view controller obviously:
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
SecondController* controller = [[SecondController alloc] init];
controller.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:controller animated:YES];
}
If using the second method, your viewDidLoad method can get rid of flexible height method as well as tabBarHidden:
- (void)viewDidLoad;
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
self.edgesForExtendedLayout = UIRectEdgeNone;
}
See the result:
The key to this conundrum is that the navigationcontroller.view.frame size doesn't change. Going of batkin's Gist here is a gist of my own.
FirstViewController.m
#import "FirstController.h"
#import "SecondController.h"
#implementation FirstController
-(id)init
{
if( (self = [super init]) )
{
self.tabBarItem.title = #"Foo";
self.tabBarItem.image = [UIImage imageNamed:#"Tab Icon.png"];
}
return self;
}
-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cell.textLabel.text = #"Click";
return cell;
}
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
SecondController* controller = [[SecondController alloc] init];
self.tabBarController.tabBar.hidden = YES;
[self.navigationController pushViewController:controller animated:YES];
}
#end
SecondViewController.m
#import "SecondController.h"
#implementation SecondController
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.view.backgroundColor = [UIColor redColor];
self.view.clipsToBounds = YES;
/* ENTER VORTEX OF DESPAIR */
// without this, there's no gap, but the view continues under the tool
// bar; with it, I get the 49-pixel gap thats making my life miserable
self.edgesForExtendedLayout = UIRectEdgeNone;
//this resizes the navigation controller to fill the void left by the tab bar.
CGRect newFrame = self.navigationController.view.frame;
newFrame.size.height = newFrame.size.height + 49;
self.navigationController.view.frame = newFrame;
/* EXIT VORTEX OF DESPAIR */
self.navigationController.toolbarItems = #[
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:nil action:nil]
];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
self.navigationController.toolbarHidden = NO;
// will log a height of 411, instead of the desired 460
NSLog(#"frame: %#", NSStringFromCGRect(self.view.frame));
NSLog(#"frame: %#", NSStringFromCGRect(self.navigationController.view.frame));
}
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
self.tabBarController.tabBar.hidden = NO;
self.navigationController.toolbarHidden = YES;
//this resizes the navigation controller back to normal.
CGRect newFrame = self.navigationController.view.frame;
newFrame.size.height = newFrame.size.height - 49;
self.navigationController.view.frame = newFrame;
//this is optional and resizes the view to fill the void left by the missing toolbar.
CGRect newViewFrame = self.view.frame;
newViewFrame.size.height = newViewFrame.size.height + 49;
self.view.frame = newViewFrame;
}
#end
If you are using Auto Layout,make sure you pin the view to its superview instead of Top Layout Guide or Bottom Layout Guide.
Have you tried to move your call hidesBottomBarWhenPushed in the viewDidLoad or before the secondViewController is pushed?
With ios7, a lot of timing issues appear if you don't do the calls at teh good moment.
You mention that you can fix this by not touching the edgesForExtendedLayout. Is there a necessary reason that the content/controls of the view controller are contained in the root view of the pushed view controller? You might consider wrapping everything in a view that is the first and only child of the main view. Then adjust that view's frame in the viewDidLayoutSubviews of the pushed view controller to avoid having content permanently beneath the toolbar using the top/bottomLayoutGuide of the view controller.
I built a new project using your Gist, and I encased the UITabBarController in a UINavigationController:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
UITabBarController* tabController = [[UITabBarController alloc] init];
tabController.viewControllers = #[
[[UINavigationController alloc] initWithRootViewController:[[FirstViewController alloc] init]],
[[UINavigationController alloc] initWithRootViewController:[[FirstViewController alloc] init]]
];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:tabController];
[navController setNavigationBarHidden:YES];
self.window.rootViewController = navController;
return YES;
}
And to show the SecondViewController, here is what I did:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
SecondViewController* controller = [[SecondViewController alloc] init];
// Reaching the UITabBarViewController's parent navigationController
[self.parentViewController.navigationController pushViewController:controller animated:YES];
}
Finally, in the secondViewController:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.view.backgroundColor = [UIColor redColor];
self.view.clipsToBounds = YES;
// The following line only works in iOS7
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
self.edgesForExtendedLayout = UIRectEdgeNone;
}
[self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:nil action:nil]];
UIBarButtonItem * logoutButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:nil action:nil];
NSMutableArray * arr = [NSMutableArray arrayWithObjects:logoutButton, nil];
[self setToolbarItems:arr animated:YES];
[self.navigationController setNavigationBarHidden:NO animated:YES];
[self.navigationController setToolbarHidden:NO animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
[self.navigationController setNavigationBarHidden:YES animated:YES];
[self.navigationController setToolbarHidden:YES animated:YES];
}
Here's what it does look:
EDIT: Changed the example and changed the screenshot. Made the example iOS6 compatible.
I manually manage hide/unhide of bottom-tab-bar along with fade animation by
...
[self.tabBarController.tabBar setHidden:NO];
[self.tabBarController.tabBar setAlpha:0.1];
[UIView animateWithDuration:0.2 animations:^{
[self.tabBarController.tabBar setAlpha:1.0];
}];
...
Bottom Toolbar on SecondVC was added in IB. No problem so far. Using Storyboard.
I think you can set SecondController's edgesForExtendedLayout to UIRectEdgeBottom.
This helps me:
Choose you view controller in storyboard -> Go to properties -> Uncheck "Adjust Scroll View Insets"
As #Leo Natan is pointing out, it seems as if hiding the tab bar and showing a toolbar is discouraged.
Nevertheless, there is a very easy solution that is working:
Just check "Under Opaque Bars" in the view controller properties in the storyboard as shown below:

Resources