I have a UITableViewController that launches a UIViewController and I would like to trap whenever the back button is pressed in the child controller, which is the class that derives from 'UIViewController'. I can change the Back Button title but setting the target & action values when setting the backBarButtonItem seems to get ignored. What's a way to receiving some kind of notification that the Back button was tapped?
- (void)showDetailView
{
// How I'm creating & showing the detail controller
MyViewController *controller = [[MyViewController alloc] initWithNibName:#"MyDetailView" bundle:nil];
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:#"Pages"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(handleBack:)];
self.navigationItem.backBarButtonItem = backButton;
[backButton release];
[self.navigationController pushViewController:controller animated:animated];
[controller release];
}
- (void)handleBack:(id)sender
{
// not reaching here
NSLog(#"handleBack event reached");
}
You can implement the viewWillDisappear method of UIViewController. This gets called when your controller is about to go away (either because another one was pushed onto the navigation controller stack, or because the 'back' button was pressed).
To determine whether the view is disappearing because of the back button being pressed, you can use a custom flag that you set wherever you push a new controller onto the navigation controller, like shown below
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if (viewPushed) {
viewPushed = NO; // Flag indicates that view disappeared because we pushed another controller onto the navigation controller, we acknowledge it here
} else {
// Here, you know that back button was pressed
}
}
And wherever you push a new view controller, you would have to remember to also set that flag...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
...
viewPushed = YES;
[self.navigationController pushViewController:myNewController animated:YES];
...
}
It has been a while since this was asked, but I just tried to do this myself. I used a solution similar to Zoran's, however instead of using a flag I did this:
- (void)viewWillDisappear: (BOOL)animated
{
[super viewWillDisappear: animated];
if (![[self.navigationController viewControllers] containsObject: self])
{
// the view has been removed from the navigation stack, back is probably the cause
// this will be slow with a large stack however.
}
}
I think it bypasses the issues with flags and IMO is cleaner, however not as efficient (if there are lots of items on the navigation controller).
In my opinion the best solution.
- (void)didMoveToParentViewController:(UIViewController *)parent
{
if (![parent isEqual:self.parentViewController]) {
NSLog(#"Back pressed");
}
}
But it only works with iOS5+
I use this code:
- (void) viewWillDisappear:(BOOL)animated {
if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound)
{
// your view controller already out of the stack, it meens user pressed Back button
}
}
But this is not actual when user presses tab bar button and pops to root view controller at one step. For this situation use this:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(viewControllerChange:)
name:#"UINavigationControllerWillShowViewControllerNotification"
object:self.navigationController];
- (void) viewControllerChange:(NSNotification*)notification {
NSDictionary* userInfo = [notification userInfo];
if ([[userInfo objectForKey:#"UINavigationControllerNextVisibleViewController"] isKindOfClass:[<YourRootControllerClass> class]])
{
// do your staff here
}
}
Don't forget then:
[[NSNotificationCenter defaultCenter] removeObserver:self
name:#"UINavigationControllerWillShowViewControllerNotification"
object:self.navigationController];
You can make your own button and place it as the leftBarButtonItem. Then have it call your method where you can do whatever, and call [self.navigationController popViewController... yourself
{
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:#"back"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(handleBack:)];
self.navigationItem.leftBarButtonItem = backButton;
[backButton release];
[self filldata];
[super viewDidLoad];
}
just replace backBarButtonItem with leftBarButtonItem
Simply use viewDidDisappear instead. It will be perfectly called in any scenario.
We are basing your lifecycle management on viewDidAppear and viewDidDisappear. If you know Android: the both are comparable to onResume and onPause methods. But there is a difference when it comes to locking the screen or pressing the homebutton on iOS.
Related
I want to pop to specific class in my app.
It works fine in iOS 8 but
Problem
in iOS 7: it gives me error like "Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted"
My code is as follow
for (UIViewController *controller in self.navigationController.viewControllers)
{
if ([controller isKindOfClass:[MyAccountVC class]])
{
[self.navigationController popToViewController:controller animated:YES];
break;
}
}
Point 1: viewWillDisapear is called before the view has popped from the navigation stack. Writing another popToViewController method inside this will cause a transition clash as both the transitions are animated:YES.
Point 2: The back button action of the UINavigationController can be modified by implementing the custom back button as shown in code here:
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *navigationBarbackButton = [[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStylePlain target:self action:#selector(backToView:)]; // you can also use a custom image for back button
self.navigationItem.backBarButtonItem = navigationBarbackButton;
}
- (IBAction)backToView:(id)sender
{
for (UIViewController *controller in self.navigationController.viewControllers)
{
if ([controller isKindOfClass:[MyAccountVC class]])
{
[self.navigationController popToViewController:controller animated:YES];
break;
}
}
}
What is happening in my app is that the user logs in and then the title of the controller becomes "Hello (Username)" and then the user presses a button and is pushed to a UITableViewController with the title: "Messages". After they select a message they are pushed to another UITableViewController, with the title "Message to (receiver)".
The problem is that when you press the back button on the 2nd UITableViewController that is titled "Message to (receiver), the title for the first UITableViewController becomes "Hello (Username)" instead of "Messages". This bug only happened when I updated to Xcode 6, and I have no idea what is causing it.
In ViewController 1 :
-(void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
UIBarButtonItem *_backButton = [[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStyleDone target:nil action:nil];
self.navigationItem.backBarButtonItem = _backButton;
_backButton = nil; //This is to make the Back button on other viewController to read "Back"
}
-(void) viewDidLoad
{
[super viewDidLoad];
self.title = [[NSString alloc] initWithFormat:#"Hello %#", self.userLoggedIn];
//Hide backbutton
[self.navigationItem setHidesBackButton:YES animated:NO];
}
- (IBAction)messages:(id)sender
{
TableViewController *tableVC = [self.storyboard instantiateViewControllerWithIdentifier:#"checkForMessagesVC"];
[self.navigationController pushViewController:tableVC animated:YES];
}
In UITableViewController 1 :
-(void)viewDidLoad
{
self.title = #"Messages";
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
ViewMessagesVC *viewMessagesVC = [self.storyboard instantiateViewControllerWithIdentifier:#"viewMessagesVC"];
[self.navigationController pushViewController:viewMessagesVC animated:YES];
}
One more thing is that in ViewController 1 the back button is hidden. Then when you go to TableViewController 1 the back button shows, but when you go to TableViewController 2 and then go back to TVC 1 the back button is hidden. (Even if you put [self.navigationItem setHidesBackButton:NO animated:NO]; in the TableViewController's viewDidLoad the back button still won't show)
Not sure what is causing this, the only thing that is happening are pushes through a navigation controller and pressing the back button. There are timers and other things happening in each controller, but nothing effecting the title. Any ideas?
So hopefully nobody else foolishly runs into this weird error. For some reason the code in my 2nd TableViewController:
- (BOOL)prefersStatusBarHidden
{
return YES;
}
caused the error
The problem I am experiencing is that when i try to pop a view controller using the default back swipeGesture in iOS7 viewDidDisappear of the present ViewController does not always get called after viewWillDisappear. I am using the UINavigationController as rootViewController.
App remain struck and does not receive any user inputs after this scenario. Sometimes app gets crashed, when i look at the log: it shows "Can't add self as subview' and in crash log, it showss EXC_BAD_ACCESS. How to fix this, but when i use back button in navigation bar app works normally.
- (void)viewWillDisappear:(BOOL)animated
{
// [self.navigationController.navigationBar setAlpha:1.0f];
[self createBarButtonITems];
self.navigationItem.title = #"Back";
}
- (void)viewDidDisappear:(BOOL)animated
{
[self zoomOutTableWithoutAnimation];
}
-(void)zoomOutTableWithoutAnimation
{
backgroundView.frame = CGRectMake(0,0,320,480);
backgroundView.transform=CGAffineTransformMakeScale(1, 1);
sideMenuTableView.transform=CGAffineTransformMakeScale(0.5,0.5);
sideMenuTableView.frame = CGRectMake(0,150,self.view.frame.size.width/2, self.view.frame.size.height);
sideMenuTableView.hidden = YES;
}
As you mentioned swipe back gesture, this is probably due to the interactive pop back.
As it is mentioned in WWDC 2013, session Custom Transitions Using View Controllers, you cannot assume a viewWillDisappear will be followed by viewDidDisappear. The same goes to viewWillAppear and viewDidAppear.
I'm not sure why you want to call
[self createBarButtonITems]
in viewWillDisappear, did you mean viewWillAppear?
Anyway, it seems to me that [self createBarButtonITems] did some side effect.
Try the following code in viewWillDisappear to undo the side effect:
- (void)viewWillDisappear
{
[self doSomethingHasSideEffect];
id <UIViewControllerTransitionCoordinator> coordinator;
coordinator = [self transitionCoordinator];
if(coordinator && [coordinator initiallyInteractive])
{
[coordinator notifyWhenInteractionEndsUsingBlock:
^(id <UIViewControllerTransitionCoordinatorContext> ctx)
{
if(ctx.isCancelled)
{
[self undoAnySideEffect]
}
}];
}
}
From your code what I can understand is you need a back button with title #"Back" instead of the previous view controllers title
just add this code tho your view controller, in which you trying to do the above stuff view did load method
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:(IS_IOS_7 ? #"" : #"Back") style:UIBarButtonItemStylePlain target:Nil action:nil];
self..navigationItem.backBarButtonItem = backButton;
Add [super viewWillDisappear:animated];
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self createBarButtonITems];
self.navigationItem.title = #"Back";
}
I have an two controllers 1st is self and 2nd is maincontroller, where I'm pushing maincontroller in stack, so the back button is automatically coming.
Here I need to make an alert when the user presses the back button.
How can I do this?
Or you can use the UINavigationController's delegate methods. The method willShowViewController is called when the back button of your VC is pressed.
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
First hide the back button by using
self.navigationItem.hidesBackButton = YES;
and then create your own Custom Button:
UIBarButtonItem *backBtn =[[UIBarButtonItem alloc]initWithTitle:#"back" style:UIBarButtonItemStyleDone target:self action:#selector(popAlertAction:)];
self.navigationItem.leftBarButtonItem=backBtn;
[backBtn release];
and your selector is here:
- (void)popAlertAction:(UIBarButtonItem*)sender
{
//Do ur stuff for pop up
}
Best and Easiest way
Try putting this into the view controller where you want to detect the press:
-(void) viewWillDisappear:(BOOL)animated {
if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
// back button was pressed. We know this is true because self is no longer
// in the navigation stack.
}
[super viewWillDisappear:animated];
}
Create your own UIBarButtonItem and set it as the leftBarButtonItem in viewDidLoad method of mainController.
For example (here I used a system item but you can also create a different one, see class reference for details).
UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showAlertView:)];
self.navigationItem.leftBarButtonItem = leftBarButtonItem;
// only if you don't use ARC
// [leftBarButtonItem release];
where
- (void)showAlertView:(id)sender
{
// alert view here...
}
add a custom back button with an action and set your alert in that action method.You can add your custom back button from here: http://www.applausible.com/blog/?p=401
viewControllerCount - is the var that holds the number of viewControllers previously was in the UINavigationController. Then, we check if viewControllerCount > [viewControllers count] if so, we know that we will get back (i.e. Back button imitation).
- (void)navigationController:(UINavigationController *)navigationController
willShowViewController:(UIViewController *)viewController
animated:(BOOL)animated
{
NSArray *viewControllers = [navigationController viewControllers];
if (viewControllerCount > [viewControllers count])
{
// your code
}
viewControllerCount = [viewControllers count];
}
extension ViewController: UINavigationControllerDelegate {
// when the self != viewcontroller ,it's mean back
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if self != viewController {
// your code
}
}}
create a button and give the button action as follows.
[self alert];
and when the alert is displayed, after tapping over yes
[self.navigationController popViewController];
after this,
self.navigationController.LeftBarButton = myButton;
this may help
I want to navigate to the particular page in my application and i also dont want to create any custom back button for that.If I can override the method of the navigation bar back button so I can call the poptorootviewcontroller.so i can go to specific page. Anyone knows what is the method that is called by the navigation bar button and if we can use it?
You can try this.. Write your logic in this native method.
-(void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:YES];
// Your Code
}
You will have to provide the name and the implementation for the button method As there is no standard method ..
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStylePlain target:self action:#selector(backButtonPressed)] autorelease];
implementation ..
-(void) backButtonPressed {
NSLog(#"Back button presses");
}
Try to use the below code:
NSArray * viewController = self.navigationController.viewControllers;
if([viewController count] > 3)
{
UIViewController * vc = [viewController objectAtIndex:0];
[self.navigationController popToViewController:vc animated:YES];
}