Check What Current rootViewController is? - ios

I would like to check what the current rootViewController is.
I have a side menu viewController that slides out from the left of the screen and it displays 4 buttons - each point to a different viewController. When they are tapped, for example button1:
- (IBAction)button1Tapped:(id)sender {
[self.sideMenuViewController setContentViewController:[[UINavigationController alloc] initWithRootViewController:[[myViewController1 alloc] init]]
animated:YES];
[self.sideMenuViewController hideMenuViewController];
}
So I'm trying to do this:
User is on myViewContollerX and opens the sideMenuViewController.
On sideMenuViewController, buttonX is grey because the user was currently on myViewControllerX.
User taps buttonY and myViewControllerY shows.
On sideMenuViewController, buttonY is now grey because the user was currently on myViewControllerY.
So I'd need to check what the current rootViewController is, I assume. How would I do this? Thanks.

How to check your current rootViewController and use it in an if statement :
// Get your current rootViewController
NSLog(#"My current rootViewController is: %#", [[[UIApplication sharedApplication].delegate.window.rootViewController class]);
// Use in an if statement
UIViewController *rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
if ([rootViewController isKindOfClass:[MyViewController class]])
{
NSLog(#"Your rootViewController is MyViewController!!");
}

Not sure which side-panel library you're using, but perhaps you can just do the styling of the buttons when they're tapped. Like this:
- (IBAction)button1Tapped:(UIButton *)sender
{
// .... set the center controller
[self setButtonAsActive:sender];
}
- (void)setButtonAsActive:(UIButton *)activeButton
{
for (UIButton *button in #[self.button1, self.button3, self.button3])
{
if (button == activeButton)
// ... make it highlighted
else
// ... make it not highlighted
}
}

You are using a setter to set contentViewController. Simply use a getter and read it.
e.g.
UIVIewController *contentViewController = self.sideMenuViewController.contentViewController;
NSLog(#"ContentViewController class: %#", [contentViewController class]);
you can check its class using:
if([contentViewController isKindOfClass: [UINavigationController class]])
{
// check nav root and disable button
}
Note:
It sounds like it would be much easier to just disable the button when its clicked and enable all the other buttons, but I'm not sure if you need this info for another reason as well.

Related

Trying to make a music player for ios but fetch some troubles

Here is my Project Overview ->
I have a viewcontroller(class A) for music list, from there user tap a music and then a url sent to another viewcontroller(class Audioplayer). and Audioplayer class play the song.
code start:
- (void) didSelectItem:(ListItem *)item {
AudioPlayerViewController *apvc = [[AudioPlayerViewController alloc] init];
apvc.songurl = item.urls;
[self presentModalViewController:apvc animated:YES];
}
code end.
in Audioplayer class have a back button in navigation bar. when back button pressed this code execute
-(IBAction)back:(id)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
Now the problem is I have a "Now Playing" Button In class A Navigation Bar(like iphone Music Apps) and i want to navigate Audioplayer class with all controll in current state by pressing "Now Playing" Button.
Note That i have already try this But it create a new AudioPlayer class object with new controlles.
code is here
-(void) Player{ AudioPlayerViewController *audvc = [[AudioPlayerViewController alloc] init];
[self presentViewController:audvc animated:YES completion:nil];}
but i want that view that i already dismiss by pressing back Button.
Experts please help Me, if you not understand my problem then please knok me, sorry for my bad english.
This AudioPlayerViewController is already created in your storyboard so you shouldn't instantiate it like this.
You could pass the data to your view controller by asking the storyboard to return you a reference to it like this:
AudioPlayerViewController *apvc = [self.storyboard instantiateViewControllerWithIdentifier:#"TheVCIdentifier"];
apvc.songurl = item.urls;
//the presentModalViewController method is deprecated.
[self presentViewController:apvc animated:YES completion:nil];
You add the view controller's identifier in Interface Builder under the Identity Inspector > Storyboard ID.
Another option would be to create a manual segue with an identifier to your View Controller and implement the prepareForSegue method in the View Controller you're transitioning from and implement it like this:
- (void) didSelectItem:(ListItem *)item {
[self performSegueWithIdentifier:#"YourSegueIdentifier" sender:self];
}
and in the prepareForSegue method:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"YourSegueIdentifier"]) {
AudioPlayerViewController *apvc = [segue destinationViewController];
apvc.songurl = item.urls;
}
}
You can check Apple's documentation on this matter here and here

Changing content of UINavigationController's Stack result in crash

I have a UINavigationController with 4 items:
(root)mainvc -> callerlistvc -> addcallerformvc -> verifycallervc (in that specific order)
When I am on the verifycallervc screen, if I press back, I want to go back to callerlistvc.
Here is the catch however, the back button should be a system button.. So.. as far as I know I cannot replace the action with a selector calling poptoviewcontroller:animated (only works on a custom uibarbuttonitem)
So then I thought of manipulating the stack (pretty interesting and challenging too!) So here is what I did...
So currently Im on the verifycallervc screen... and this gets called.
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSMutableArray *allViewControllers = [self.navigationController.viewControllers mutableCopy];
__block UIViewController *mainvc = nil;
__block UIViewController *callerlistvc = nil;
__block UIViewController *addcallerformvc = nil;
[allViewControllers enumerateObjectsUsingBlock:^(UIViewController *vc, NSUInteger idx, BOOL *stop) {
if ([vc isKindOfClass:[MainVC class]]) {
mainvc = vc;
} else if ([vc isKindOfClass:[CallerListVC class]]) {
callerlistvc = vc;
} else if ([vc isKindOfClass:[AddCallerFormVC class]]) {
addcallerformvc = vc;
}
}];
[self.navigationController setViewControllers:#[ mainvc, callerlistvc, self]];
}
After I did that, I pressed back normally and was now on the callerlistvc... great.
Unfortunately when I press the button (push-segued to addcallerformvc)... it results in a crash EXC_BAD_ACCESS.
I also tried a different approach by first manipulating the variable callerlistvc like so before adding it in the setViewControllers method
callerlistvc = [[UIStoryboard storyboardWithName:#"main" bundle:nil] instantiateViewControllerWithIdentifier:#"CallerListVC"];
But the result is the same.
I have added breakpoints and it goes like this...
CallerListVC:
tappedShowAddCallerListButton
performSegueWithIdentifier
prepareForSegue // identifier string is correct, destinationVC is not nil
then AddCallerFormVC:
4. viewDidLoad
5. viewWillAppear // properties not nil
after that EXC_BAD_ACCESS occurs
How can I make this work?
The better approach in this case would be to use a custom UINavigationController class and extend the popViewControllerAnimated: method. In this method either call the super method or pop to the specific view controller (super class method) based on a check. That way you have your system nav buttons and also control where the tack should pop to.
Don't override anything in verifycallervc and instead do following with normal back on verifycallervc
Override viewWillAppear or viewDidAppear for addcallerformvc like this
- (void)viewDidAppear:(BOOL)animated
{
if (![self isBeingPresented]) {
[self.navigationController popViewControllerAnimated:YES];
}
}
Reference :
https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/RespondingtoDisplay-Notifications/RespondingtoDisplay-Notifications.html#//apple_ref/doc/uid/TP40007457-CH12-SW7
Note: not tested, don't have XCode right now....

PopViewController strange behaviour

Due to a weird request which I tried to turn down but it didn't work, I had to override the navigationBar's back Button.
I have made a custom UINavigationController subclass and hacked the
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item method.
Here is my code:
#interface CustomUINavigationController ()
#end
#implementation CustomUINavigationController
#pragma mark - UINavigationBar delegate methods
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
if ([[self.viewControllers lastObject] isKindOfClass:[ViewController1 class]]) {
ViewController1 *vc1 = (ViewController1 *)[self.viewControllers lastObject];
[vc1 handleBackAction];
if (vc1.canPopVC == YES) {
[self popViewControllerAnimated:YES];
return YES;
} else {
return NO;
}
}
[self popViewControllerAnimated:YES];
return YES;
}
#end
All works fine, except when I pop a viewController programmatically. The app crashed every time when I wanted to perform a push after said pop. Turning NSZombie on, revealed that when popping a viewController programmatically, its parent viewController is deallocated.
At this point, making a custom backButton is not a option since it will lose the native iOS 7 swipe to popViewController feature.
Crash log:
*** -[ContactsDetailViewController performSelector:withObject:withObject:]: message sent to deallocated instance 0x1806b790
(My previous post was completely wrong. This is a complete rewrite with an appropriate solution.)
I had this behavior pop up when I chose to delete some code generating a warning when I was converting to ARC -- code that I thought was not being called.
Here's the situation:
If you shadow navigationBar:shouldPopItem: in a subclass of UINavigationController, then the current view controller will NOT be popped when the user touches the NavBar's BACK button. However, if you call popViewControllerAnimated: directly, your navigationBar:shouldPopItem: will still be called, and the view controller will pop.
Here's why the view controller fails to pop when the user touches the BACK button:
UINavigationController has a hidden method called navigationBar:shouldPopItem:. This method IS called when the user clicks the BACK button, and it is the method that normally calls popViewControllerAnimated: when the user touches the BACK button.
When you shadow navigationBar:shouldPopItem:, the super class' implementation is not called, and hence the ViewController is not popped.
Why you should NOT call popViewControllerAnimated: within your subclass' navigationBar:shouldPopItem::
If you call popViewControllerAnimated: within navigationBar:shouldPopItem:, you will see the behavior that you desire when you click the BACK button on the NavBar: You can determine whether or not you want to pop, and your view controller pops if you want it to.
But, if you call popViewControllerAnimated: directly, you will end up popping two view controllers: One from your direct call to popViewControllerAnimated:, and one from the call you added to within navigationBar:shouldPopItem:.
What I believe to be the safe solution:
Your custom nav controller should be declared like this:
#interface CustomNavigationController : UINavigationController <UINavigationBarDelegate>
{
// .. any ivars you want
}
#end
Your implementation should contain code that looks something like this:
// Required to prevent a warning for the call [super navigationBar:navigationBar shouldPopItem:item]
#interface UINavigationController () <UINavigationBarDelegate>
#end
#implementation CustomNavigationController
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
BOOL rv = TRUE;
if ( /* some condition to determine should NOT pop */ )
{
// we won't pop
rv = FALSE;
// extra code you might want to execute ...
} else
{
// It's not documented that the super implements this method, so we're being safe
if ([[CustomNavigationController superclass]
instancesRespondToSelector:#selector(navigationBar:shouldPopItem:)])
{
// Allow the super class to do its thing, which includes popping the view controller
rv = [super navigationBar:navigationBar shouldPopItem:item];
}
}
return rv;
}
I'm not 100% certain but I don't think you should actually be popping the view controller in that delegate method.
"should" delegate methods don't normally do something. They just assert whether something should or shouldn't be done.
Change your method to this...
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
if ([[self.viewControllers lastObject] isKindOfClass:[ViewController1 class]]) {
ViewController1 *vc1 = (ViewController1 *)[self.viewControllers lastObject];
[vc1 handleBackAction];
if (vc1.canPopVC == YES) {
return YES;
} else {
return NO;
}
}
return YES;
}
And see if it works.
All I have done is removed the popViewController calls.
EDIT - How to add a custom back button
In a category on UIBarButtonItem...
+ (UIBarButtonItem *)customBackButtonWithTarget:(id)target action:(#SEL)action
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:#"Some image"] forState:UIControlStateNormal];
[button setTitle:#"Some Title" forState:UIControlStateNormal];
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
return barButtonItem;
}
Now whenever you want to set a custom back button just use...
UIBarButtonItem *backButton = [UIBarButtonItem customBackButtonWithTarget:self action:#selector(backButtonPressed)];
I would suggest a completely different approach.
Create a base class for the view controllers that you are pushing on the navigation stack. In the viewDidLoad method set your custom button as the leftBarButtonItem of the navigationItem and add a -backAction: which invokes the popViewControllerAnimated: method of the navigation controller.
That way you won't care about things like losing functionality of UINavigationController like the swipe to pop and you won't have to override the navigationBar:shouldPopItem: method at all.
You probably need to do [super shouldPop... instead of actual [self popViewControllerAnimated:YES];.
The reason being that the way UINavigationController implements stack is private, so you should mess with the method calls as little as possible.
Anyway, this looks like a hack. Moreover, the user will have no visual clue that you are blocking the navigation action. What's wrong with disabling the button via:
self.navigationController.navigationItem.backBarButtonItem.enabled = NO;
It's my fix to #henryaz answer for Xcode 11:
#interface UINavigationControllerAndNavigationBarDelegate : UINavigationController<UINavigationBarDelegate>
#end
#interface CustomNavigationController : UINavigationControllerAndNavigationBarDelegate
#end
// changed this method just a bit
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
BOOL shouldPop = // detect if need to pop
if (shouldPop) {
shouldPop = [super navigationBar:navigationBar shouldPopItem:item]; // before my fix this code failed with compile error
}
return shouldPop;
}

Back button in standalone UINavigationBar with UINavigationController

I am trying to implement a push-up UINavigationBar, where the position of the navigation bar is attached to the contentOffset of the UIScrollView (similar to how safari works in ios7).
In order to get the dynamic movement working I am using a UINavigationBar created programatically and added as a subview of the UIViewController's view (it is accessible as self.navbar).
The UIViewController is within a UINavigationController hierarchy, so I am hiding the built-in self.navigationController.navigationBar at the top of -viewWillAppear:.
The problem I am trying to solve is to add a back button to this new standalone navbar. I would preferably like to simply copy the buttons or even the navigationItems from the navigationController and its hidden built-in navbar, but this doesnt seem to work
Is my only solution to set leftBarButtonItem on my standalone navbar to be a fake back button (when there is a backItem in the navController's navbar)? This seems a bit hacky, and I'd rather use the built backButton functionality.
Another way to do that, once you have your own UINavigationBar set, is to push two UINavigationItems on your navigationBar, causing back button to appear. You can then customize what happens when the back button is pressed.
Here's how I did that
1 - Some UINavigationItem subclass, to define extra-behavior / customization parameters
#interface MyNavigationItem : UINavigationItem
//example : some custom back action when 'back' is pressed
#property (nonatomic, copy) void (^onBackClickedAction)(void);
#end
2 - Then wire that into your UINavigationBarDelegate :
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
if ([item isKindOfClass:[MyNavigationItem class]]) {
MyNavigationItem *navItem = (MyNavigationItem *)item;
//custom action
if (navItem.backAction) {
navItem.backAction();
}
return YES;// return NO if you don't want your bar to animate to previous item
} else {
return YES;
}
}
You could adapt that scheme, calling your UINavigationController pop method on back action.
This is still hacky
Vinzzz' answer was a good solution. Here is my implementation, as the context was slightly different.
In the UIViewController's viewDidLoad method I setup my navbar's navigation items like this:
NSMutableArray* navItems = [#[] mutableCopy];
if (self.navigationController.viewControllers.count > 1)
{
NSInteger penultimateIndex = (NSInteger)self.navigationController.viewControllers.count - 2;
UIViewController* prevVC = (penultimateIndex >= 0) ? self.navigationController.viewControllers[penultimateIndex] : nil;
UINavigationItem* prevNavItem = [[UINavigationItem alloc] init];
prevNavItem.title = prevVC.title;
[navItems addObject:prevNavItem];
}
UINavigationItem* currNavItem = [[UINavigationItem alloc] init];
... <Add any other left/right buttons to the currNavItem> ...
[navItems addObject:currNavItem];
[self.navbar setItems:navItems];
...where self.navbar is my floating stand-alone UINavigationBar.
I also assign the current view controller to be self.navbar's delegate, and then listen for the -navigationBar:shouldPopItem: event that is triggered when the back button is pressed:
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
if (navigationBar == self.navbar)
{
[self.navigationController popViewControllerAnimated:YES];
return NO;
}
return YES;
}
(If you return YES, it will crash when a swipe gesture is used in ios7).

How to switch from one tab to another and back?

I've got a little problem on navigating through my views.
Here is my configuration :
Ive got 1 Tabbar Controller with 2 relationship segues to 2 simple views embedded inside a navigation controller.
Now i want to navigate from view controller 1 to view controller 3 and i also want to show the correct tab selected inside the tabbar. And if i come from view controller 1, i also want that the back button redirects me the the previous tab. I tried something with a segue connected between that views, but if i do so, it just pushes the view controller onto the navigation stack but not changes the tab. So my question now is, what is the best way of managing this Problem
Screenshot:
Here's a way to do it. But I'm posting this really to illustrate why you shouldn't do it.
I'm using VC2's and VC3's view tag property to pass navigation data around, which has the effect of tightly coupling all three objects.
I override back bar button for the VC1->VC3 context. You lose consistency.
VC3->VC2 provides back animation. VC3->VC1 has no animation as it flips from one tab to another. More inconsistency
VC1->VC3, tap Tab Item 2 transitions to VC2. UI confusion.
Anyway if you still want to do this...
.
ViewController1
Has a "jump to VC3" button, wire up to jumpToVC3:
//ViewController1.m
#import "ViewController1.h"
#implementation ViewController1
- (IBAction)jumpToVC3:(id)sender {
NSArray* viewArray = [[[self.tabBarController viewControllers] objectAtIndex:1] viewControllers];
[[[viewArray lastObject] view] setTag:1];
[self.tabBarController setSelectedIndex:1];
}
#end
"jumptToVC3" switches us to tab 2 and sets the frontmost view's view tag property to 1. IF the frontmost view is VC2, this triggers an immediate segue to VC3. If the frontmost view is VC3, this sets up the back button correctly. If other View Controllers get added to this stack, this navigation will break.
ViewController2
Has a "move to VC3" button, wired to a storyboard segue to VC3 "toVC3"
// ViewController2.m
#import "ViewController2.h"
#import "ViewController3.h"
#implementation ViewController2
//we use the view.tag property as a switch:
//0 = do nothing
//1 = segue to VC3
//2 = go to tab 0
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (self.view.tag ==1){
[self performSegueWithIdentifier:#"toVC3" sender:self];
} else if (self.view.tag == 2){
[self.tabBarController setSelectedIndex:0];
}
self.view.tag = 0;
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if (self.view.tag ==1) {
[[segue.destinationViewController view] setTag:1];
} else {
[[segue.destinationViewController view] setTag:0];
}
self.view.tag = 0;
}
- (void) viewWillDisappear:(BOOL)animated
{
self.view.tag = 0;
}
#end
ViewController3
Overrides the back button if it's view.tag is set to 1. If you want both context's back buttons to be consistent, you will need to override for the default behaviour as well. You will not be able to get a standard back button look for this override behaviour.
// ViewController3.m
#import "ViewController3.h"
#implementation ViewController3
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (self.view.tag == 1) {
self.navigationItem.leftBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:#"0.0"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(goBack:)];
}
self.view.tag = 0;
}
- (IBAction)goBack:(id)sender {
[[[[self.navigationController viewControllers]
objectAtIndex:0] view] setTag:2];
[self.navigationController popToRootViewControllerAnimated:YES];
}
#end

Resources