繁体   English   中英

我如何在AppDelegate中知道UIViewController过渡到另一个UIViewController?

[英]How do I know in AppDelegate when UIViewController transit to another UIViewController?

无论如何,在AppDelegate中是否知道在不调用AppDelegate和UIViewController的任何额外方法的情况下推送了新的UIViewController?

AppDelegate能够在不编写任何特定UIViewController代码的情况下就知道要推送哪个新的UIViewController吗?

好吧,我为您提供了一种简便的方法,因为您不想在ViewController中编写任何代码。 在下面查看我的类别

UINavigationController + PushNotifier.h

#import <UIKit/UIKit.h>

@interface UINavigationController (PushNotifier)
extern void PJSwizzleMethod(Class cls, SEL originalSelector, SEL swizzledSelector);

@end

UINavigationController + PushNotifier.m

#import "UINavigationController+PushNotifier.h"
#import <objc/runtime.h>


@implementation UINavigationController (PushNotifier)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        PJSwizzleMethod([self class],
                        @selector(pushViewController:animated:),
                        @selector(pj_pushViewController:animated:));
    });
}

- (void)pj_pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    //notify your Application Delegate
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ViewControllerWillPush" object:nil userInfo:@{@"pushingViewController":viewController}];
    return [self pj_pushViewController:viewController animated:animated];
}

@end

void PJSwizzleMethod(Class cls, SEL originalSelector, SEL swizzledSelector)
{
    Method originalMethod = class_getInstanceMethod(cls, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(cls, swizzledSelector);

    BOOL didAddMethod =
    class_addMethod(cls,
                    originalSelector,
                    method_getImplementation(swizzledMethod),
                    method_getTypeEncoding(swizzledMethod));

    if (didAddMethod) {
        class_replaceMethod(cls,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

注意:仅当您使用导航控制器和推/显示视图控制器时,此方法才有效

没有适当的方法可以执行此操作,但可以使用以下方法作为解决方法:

 func application (_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { guard let vc = (window?.rootViewController?.presentedViewController) else { return .portrait // your default orientation, to update according to your needs } if (vc.isKind(of: NSClassFromString("The class you are looking to")!)) { // Here you can put any code you want, your view controller was just pushed return .allButUpsideDown } return .portrait // return the orientation you want } 

问题是您将需要在应用程序中为每个viewController进行强制类型转换,而imo执行一些自定义代码会更简洁,更适合您的需求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM