问题
Like many others, I would like to perform an action when the 'back' button is used in a UINavigationController. I am aware of some alternative approaches to this, such as adding my own button and trying to spoof the look, using viewWillDisappear and setting tags on all non-back actions that will cause the view do disappear, etc.
But the one that I would like to try is subclassing UINavigationController and injecting something in popViewControllerAnimated:
But I can't get a simple test case to work. Here is what I tried...
I created a new class, CustomNavigationController, which inherits from UINavigationController. In here, I updated popViewControllerAnimated:
.h:
#import <UIKit/UIKit.h>
@interface CustomNavigationController : UINavigationController
@end
.m:
#import "CustomNavigationController.h"
@interface CustomNavigationController ()
@end
@implementation CustomNavigationController
- (UIViewController *)popViewControllerAnimated:(BOOL)animated{
NSLog(@"pop!");
return [super popViewControllerAnimated:animated];
}
@end
In interface builder, I changed the class of the navigation controller:
What am I missing? I am expecting 'pop' to be logged whenever I pop any view within this nav controller.
回答1:
I've just tested the very same implementation on iPhone 5.1 simulator and it works fine - it seems the problem is somewhere else.
I've created an empty project from a single-view application template and added CustomNavigationController class with the code which you posted in the question body. An UIButton is used to push another view controller to navigation stack (using storyboard's segue), and 'POP' message is being posted in the console as expected.
回答2:
From the first paragraph of the documentation on UINavigationController.
The UINavigationController class implements a specialized view controller that manages the navigation of hierarchical content. This class is not intended for subclassing. Instead, you use instances of it as-is in situations where you want your application’s user interface to reflect the hierarchical nature of your content.
If you want this kind of customization you're better off implementing your own navigation style controller.
来源:https://stackoverflow.com/questions/10109480/uinavigationcontroller-subclass-customizing-pop