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

查看:23
本文介绍了试图处理“后退"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];
}

或者还有另一种方法可以获得导航返回按钮的操作.

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

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

Create Custom button for UINavigationItem of back button .

例如:

在 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];
}

斯威夫特:

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

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

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