Trying to handle quot;backquot; navigation button action in iOS(试图处理“后退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中的导航按钮操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:试图处理“后退"iOS中的导航按钮操作
基础教程推荐
- UINavigationBar 隐藏按钮文本 2022-01-01
- Firebase 云消息传递令牌未生成 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- 在 iOS 7 下 CCMenu 错位 2022-01-01
- 更改 UITableView 部分标题的颜色 2022-01-01
- UINavigationItem 的持久 rightBarButtonItem 属性 2022-01-01
- 从 UIWebView 访问元数据 2022-01-01
- EditText 中的 setHintTextColor() 2022-01-01
- Android - 如何在runOnUiThread 中将数据传递给Runnable? 2022-01-01
- 在视图控制器的宽度上水平均匀分布 UIButton 的最简单方法? 2022-01-01