我有一个启动UIViewController的UITableViewController,我希望每当按下子控制器中的后退按钮时都会捕获,这是从“UIViewController”派生的类。我可以更改后退按钮的标题,但是在设置backBarButtonItem时设置目标和操作值似乎被忽略了。有什么方法可以接收到点击了Back按钮的通知?
- (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");
}
发布于 2009-10-13 02:21:37
您可以实现UIViewController的viewWillDisappear
方法。当你的控制器将要离开时,这个函数会被调用(因为另一个控制器被推到了导航控制器堆栈上,或者因为“后退”按钮被按下了)。
要确定视图是否因为按下back按钮而消失,可以使用在将新控制器推到导航控制器上时设置的自定义标志,如下所示
- (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
}
}
无论您在何处推送新的视图控制器,您都必须记住也要设置该标志……
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
...
viewPushed = YES;
[self.navigationController pushViewController:myNewController animated:YES];
...
}
发布于 2012-04-27 08:25:43
自从有人问起这个问题已经有一段时间了,但我只是试着自己去做。我使用了一个类似于Zoran的解决方案,但是我没有使用标志,而是这样做的:
- (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.
}
}
我认为它绕过了标志的问题,IMO更干净,但是效率不高(如果导航控制器上有很多项目)。
发布于 2013-05-31 01:16:19
在我看来最好的解决方案。
- (void)didMoveToParentViewController:(UIViewController *)parent
{
if (![parent isEqual:self.parentViewController]) {
NSLog(@"Back pressed");
}
}
但它只适用于iOS5+
https://stackoverflow.com/questions/1557290
复制相似问题