试图处理“后退” iOS中的导航按钮操作 [英] Trying to handle "back" navigation button action in iOS

查看:118
本文介绍了试图处理“后退” iOS中的导航按钮操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检测用户何时点击导航栏上的后退按钮,以便在发生这种情况时执行某些操作。我试图手动设置一个动作到这样的按钮,这样:

I need to detect when the user taps the "back" button on the navigation bar, in order to perform some operations when that occurs. I'm trying to set manually an action to such button, this way:

[self.navigationItem.backBarButtonItem setAction:@selector(performBackNavigation:)];

- (void)performBackNavigation:(id)sender
{
   // Do operations

   [self.navigationController popViewControllerAnimated:NO];
}

我首先将该代码放在视图控制器本身,但我发现 self.navigationItem.backBarButtonItem 似乎是 nil ,所以我将相同的代码移动到父视图控制器,这推动了前导航堆栈。但我无法让它发挥作用。我已经阅读了一些关于这个问题的帖子,其中一些人说需要在父视图控制器上设置选择器,但对我来说它无论如何都不起作用......我可能做错了什么?

I firstly placed that code in the view controller itself, but I found that self.navigationItem.backBarButtonItem seemed to be nil, so I moved that same code to the parent view controller, which pushes the former to the navigation stack. But I'm neither able to make it work. I've read some posts regarding this issue, and some of them said that the selector needs to be set at the parent view controller, but for me it doesn't work anyway... What could I'm doing wrong?

谢谢

推荐答案

使用 VIewWillDisappear尝试此代码检测按下NavigationItem后退按钮的方法:

Try this code using VIewWillDisappear method to detect the press of The back button of NavigationItem:

-(void) viewWillDisappear:(BOOL)animated
{
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) 
    {
        // Navigation button was pressed. Do some stuff 
        [self.navigationController popViewControllerAnimated:NO];
    }
    [super viewWillDisappear:animated];
}

或者还有另一种获取导航BAck按钮操作的方法。

OR There is another way to get Action of the Navigation BAck button.

为后退按钮的UINavigationItem创建自定义按钮。

Create Custom button for UINavigationItem of back button .

对于Ex:


在ViewDidLoad中:

In ViewDidLoad :



- (void)viewDidLoad 
{
    [super viewDidLoad];
    UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStyleBordered target:self action:@selector(home:)];
    self.navigationItem.leftBarButtonItem=newBackButton;
}

-(void)home:(UIBarButtonItem *)sender 
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

Swift:

override func willMoveToParentViewController(parent: UIViewController?) 
{
    if parent == nil 
    {
        // Back btn Event handler
    }
}

这篇关于试图处理“后退” iOS中的导航按钮操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆