iOS 攔截系統自帶的Pop事件

攔截系統自帶的Pop事件
首先,在開發中我遇到一個問題,用故事版將控制器連接起來,之後就有了系統自帶的返回按鈕(大家都知道,說的很直白)。
當我想點擊返回按鈕的時候,根據自己的情況再確定反不反回上一個控制器。解決方案:
我看到了[南峯子的技術博客](http://southpeak.github.io/blog/archives/)
抄過來的,不是原創,只是我在找相關解決方案的時候不好找,就多寫寫了。
.h
#import <UIKit/UIKit.h>

@protocol BackButtonHandlerProtocol <NSObject>

@optional
-(BOOL)navigationShouldPopOnBackButton;
@end



@interface UIViewController (BackButtonHandler)<BackButtonHandlerProtocol>

@end


.m
//
//  UIViewController+BackButtonHandler.m
//  NavigationCtrlText
//
//  Created by 鄭鵬 on 15/12/26.
//  Copyright © 2015年 littleSun_zheng. All rights reserved.
//

#import "UIViewController+BackButtonHandler.h"
@implementation UIViewController (BackButtonHandler)
@end

//UINavigationBar的代理方法之一  的完整簽名
- (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 {
/*__系統返回按鈕會隨着返回動畫而邊淡__**littleSun_zheng**/

        for(UIView *subview in [navigationBar subviews]) {
            if(subview.alpha < 1.) {
                [UIView animateWithDuration:.25 animations:^{
                    subview.alpha = 1.;
                }];
            }
        }
    }
    return NO;
}
@end//需要使用的地方:在這個方法裏寫返回按鈕的事件處理
-(BOOL)navigationShouldPopOnBackButton 
{
    NSLog(@"捕捉到返回事件");
    UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"提示:" message:@"您確定要放棄編輯嗎?" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:@"不", nil];
    alerView.tag = 1000;
    [alerView show];

    return NO;//這裏就是阻止 “pop” 動作
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1000) {

        if(buttonIndex == 0){
            [self.navigationController popViewControllerAnimated:YES]; 
        }else{
            //什麼都不需要做了;
        }

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章