如何区分当下控制器是 视频控制器 还是 视图控制器 ?
1、首先要知道系统方法是如何控制当前的控制器
//此方法可获取当前显示控制器
supportedInterfaceOrientations
2、使用runtime中的交换方法
这里主要是替换系统的方法,这样就可以在系统方法中做一些操作,load
方法的作用是在程序运行起来将会先加载load
方法,加载完成后在加载各个类中的方法
+ (void)load
{
Method supportedInterfaceOrientations = class_getInstanceMethod(self,@selector(supportedInterfaceOrientations));
Method wt_supportedInterfaceOrientations = class_getInstanceMethod(self,@selector(wt_supportedInterfaceOrientations));
method_exchangeImplementations(supportedInterfaceOrientations, wt_supportedInterfaceOrientations);
}
3、处理系统替换之后的方法做一些操作
判断一下,如果是视频控制器的话,就返回上、下、左、右。如果不是视频控制器的话,就返回只能竖屏。
if ([NSStringFromClass(vc.class) isEqualToString: @"ViewController"])
{
return UIInterfaceOrientationMaskPortrait;
}
else
{
return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft;
}
4、过滤掉TabBar,navi
这里注意一点通常项目中都会添加TabBar、navi
,一般初学者在这里不清楚如何正确的获取当前显示的控制器,主要意思是过滤掉TabBar,navi
- (UIViewController *)getVc:(UIViewController *)vc
{
if ([vc isKindOfClass: [UITabBarController class]])
{
UIViewController *tabBarVC = vc.childViewControllers.firstObject;
return [self getVc: tabBarVC];
}
else if([vc isKindOfClass: [UINavigationController class]])
{
UIViewController *navVc = vc.childViewControllers.lastObject;
return [self getVc: navVc];
}
else
{
return vc;
}
}
代码如下:
#import "UIViewController+Extension.h"
#import <objc/message.h>
#import "ViewController.h"
@implementation UIViewController (Extension)
+ (void)load
{
Method supportedInterfaceOrientations = class_getInstanceMethod(self, @selector(supportedInterfaceOrientations));
Method wt_supportedInterfaceOrientations = class_getInstanceMethod(self, @selector(wt_supportedInterfaceOrientations));
method_exchangeImplementations(supportedInterfaceOrientations, wt_supportedInterfaceOrientations);
}
// 要交换的方法。
- (UIInterfaceOrientationMask)wt_supportedInterfaceOrientations
{
[self wt_supportedInterfaceOrientations];
UIViewController *vc = [self getVc: self];
if ([NSStringFromClass(vc.class) isEqualToString: @"ViewController"])
{
return UIInterfaceOrientationMaskPortrait;
}
else
{
return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft;
}
}
// 获取当前显示的控制器,主要过滤TabBar,navi
- (UIViewController *)getVc:(UIViewController *)vc
{
if ([vc isKindOfClass: [UITabBarController class]])
{
UIViewController *tabBarVC = vc.childViewControllers.firstObject;
return [self getVc: tabBarVC];
}
else if([vc isKindOfClass: [UINavigationController class]])
{
UIViewController *navVc = vc.childViewControllers.lastObject;
return [self getVc: navVc];
}
else
{
return vc;
}
}
@interface UIViewController (Extension)
- (UIInterfaceOrientationMask)wt_supportedInterfaceOrientations;
@end