[英]iPhone Dev, UINavigationController, How to Programmatically Tell when Back Button is Pressed
[英]Find out if user pressed the back button in uinavigationcontroller?
當視圖加載時,我想查看是否是因為用戶按下了后退按鈕。 我該如何檢查?
我發現檢測UINavigationController的后退按鈕按下(iOS 5.0之前)的最佳解決方案是驗證導航控制器的視圖控制器堆棧中不存在當前的視圖控制器。
在邏輯上- (void)viewDidDisappear:(BOOL)animated
檢查此條件可能更安全,在- (void)viewDidDisappear:(BOOL)animated
該方法時,極有可能將視圖控制器從堆棧中刪除。
iOS 5.0之前的版本:
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
if (![[self.navigationController viewControllers] containsObject:self]) {
// We were removed from the navigation controller's view controller stack
// thus, we can infer that the back button was pressed
}
}
iOS 5.0及更高版本,您可以使用-didMoveToParentViewController:
- (void)didMoveToParentViewController:(UIViewController *)parent
{
// parent is nil if this view controller was removed
}
在您的viewWillDisappear方法中檢查
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ([self isMovingFromParentViewController]) {
//specific stuff for being popped off stack
}
}
這僅適用於iOS 5之后的版本
這是一個稍微不同的情況,但是我認為該解決方案可能會幫助其他人。
在我的情況下,我在UIPopoverController中有一個UINavigationController。 我需要檢測用戶是否單擊了后退按鈕,還是單擊了彈出框之外的按鈕。 為此,我檢查了viewWillDisappear中的visibleViewController屬性。 如果關閉時視圖控制器仍然是visibleViewController,則通過另一種方式關閉彈出窗口。 如果關閉時視圖控制器不是visibleViewController,則按下后退按鈕。
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if (self.navigationController.visibleViewController != self) {
<Do something since we're closing using something else>
} else {
<Do something since we're closing because of the back button>
}
}
我嘗試使用zach的解決方案,但isMovingFromParentViewController在兩種情況下均返回true。
我驗證了此功能在iOS 5+
我希望這有幫助。
創建自定義后退按鈕並設置目標,
步驟1:將這些方法添加到您的課程中
- (void)backButtonClicked :(id)sender{
[self.navigationController popViewControllerAnimated:YES];
}
- (void)addBackBarButton{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 55, 35);
[button setTitle:@"back" forState:UIControlStateNormal];
[button addTarget:self action:@selector(backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = customBarItem;
}
步驟2:呼叫[self addBackBarButton]; 在viewDiDLoad方法中
您將在backButtonClicked方法中獲得操作。 您可以按照自己的方式玩耍。
干杯!
執行此操作的唯一方法是確定自定義按鈕,從而確定它是后退按鈕。 如果您不知道該怎么做,請查看本教程 。 它看起來不像正常的后退按鈕,而是關閉的。 如果您需要更多幫助,請發表評論
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.