你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS技巧綜合 >> 攔截UIViewController的popViewController事件

攔截UIViewController的popViewController事件

編輯:IOS技巧綜合
[摘要]本文是對攔截UIViewController的popViewController事件的講解,對學習IOS蘋果軟件開發有所幫助,與大家分享。

實現攔截UIViewControllerpop操作有兩種方式:

    自定義實現返回按鈕,即設置UIBarButtonItem來實現自定義的返回操作。 創建UINavigatonControllerCategory,來定制navigationBar: shouldPopItem:的邏輯。

UIViewController+BackButtonHandler.h:

#import <UIKit/UIKit.h>

@protocol BackButtonHandlerProtocol <NSObject>
@optional
// Override this method in UIViewController derived class to handle 'Back' button click
-(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 {
        // Workaround for iOS7.1. Thanks to @boliva - http://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;
}

使用:

    UIViewController當中引入頭文件
#import "UIViewController+BackButtonHandler.h"
    UIViewController中實現navigationShouldPopOnBackButton方法。
- (BOOL)navigationShouldPopOnBackButton{
    [[[UIAlertView alloc] initWithTitle:@"提示" message:@"確定返回上一界面?"
                               delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil] show];
    //renturn no 攔截pop事件
    return NO;
}

參考:

    iOS攔截導航欄返回按鈕事件的正確方式

    UIViewController-BackButtonHandler
    

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved