您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

如何攔截 UIViewController 的返回(pop)事件

編輯:iOS 技巧大全
[摘要]本文介紹兩種攔截 UIViewController 返回操作的思路,並給出通過 Category 定製 navigationBar:shouldPopItem: 的完整實現,可在返回前彈出確認框。

實現攔截 UIViewController 的 pop 操作,常見有兩種方式:

  • 自定義返回按鈕:直接設置 UIBarButtonItem,用自己的 item 替換系統返回按鈕,從而完全掌控點擊行為。
  • 創建 UINavigationController 的 Category,定製 navigationBar:shouldPopItem: 的判斷邏輯。

第二種方式侵入性更小,對已有頁面幾乎零改動,實用性更強。下面是一個完整實現。

UIViewController+BackButtonHandler.h

#import <UIKit/UIKit.h>

@protocol BackButtonHandlerProtocol <NSObject>
@optional
// 在 UIViewController 的子類中重寫此方法,即可攔截「返回」按鈕的點擊
- (BOOL)navigationShouldPopOnBackButton;
@end

@interface UIViewController (BackButtonHandler) <BackButtonHandlerProtocol>
@end

UIViewController+BackButtonHandler.m

#import "UIViewController+BackButtonHandler.h"

@implementation UIViewController (BackButtonHandler)
@end

@implementation UINavigationController (ShouldPopOnBackButton)

- (BOOL)navigationBar:(UINavigationBar *)navigationBar
         shouldPopItem:(UINavigationItem *)item {

    // 判斷是否為最根頁面,根頁面不允許返回
    if ([self.viewControllers count] < [navigationBar.items count]) {
        return YES;
    }

    BOOL shouldPop = YES;
    UIViewController *vc = [self topViewController];
    if ([vc respondsToSelector:@selector(navigationShouldPopOnBackButton)]) {
        shouldPop = [vc navigationShouldPopOnBackButton];
    }

    if (shouldPop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self popViewControllerAnimated:YES];
        });
    } else {
        // iOS 7.1 的兼容處理
        // 參考:https://stackoverflow.com/posts/comments/34452906
        for (UIView *subview in [navigationBar subviews]) {
            if (0. < subview.alpha && subview.alpha < 1.) {
                [UIView animateWithDuration:.25 animations:^{
                    subview.alpha = 1.;
                }];
            }
        }
    }
    return NO;
}
@end

使用方式

第一步,在需要攔截的 UIViewController 中引入頭文件:

#import "UIViewController+BackButtonHandler.h"

第二步,實現 navigationShouldPopOnBackButton 方法,返回 NO 即表示攔截:

- (BOOL)navigationShouldPopOnBackButton {
    [[[UIAlertView alloc] initWithTitle:@"提示"
                               message:@"確定返回上一界面?"
                            delegate:self
                   cancelButtonTitle:@"取消"
                   otherButtonTitles:@"確定", nil] show];
    // 返回 NO 表示攔截 pop 事件
    return NO;
}

這樣一來,用戶點擊導航欄返回按鈕時,會先彈出確認框,只有確認後才真正返回上一頁。

參考資料

  • iOS 攔截導航欄返回按鈕事件的正確方式
  • UIViewController-BackButtonHandler
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved