最近项目中遇到了SDK内需要横屏,而工程必须竖屏的情况,解决方法有两个:
1.最保险的方法,工程AppDelegate.h添加
@property (nonatomic, strong) NSNumber* allowRotation; // 横竖屏
//AppDelegate.m处实现
//////横屏方式
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
// NSLog(@"application");
// if ([_allowRotation boolValue]) {
// return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft;
// }else{
// return (UIInterfaceOrientationMaskPortrait);
// }
//}
2.SDK捕获AppDelegate方法,只要工程实现了-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window代理方法就可以了。方法没完善,就只写主要部分了。
//调用处
[self hookMehod:@selector(SDKApplication:supportedInterfaceOrientationsForWindow:) andDef:@selector(defaultApplication:supportedInterfaceOrientationsForWindow:) andNew:@selector(application:supportedInterfaceOrientationsForWindow:)];
//方法:
-(void)hookMehod:(SEL)oldSEL andDef:(SEL)defaultSEL andNew:(SEL)newSEL {
Class oldClass = objc_getClass([@"AppDelegate" UTF8String]);
Class newClass = [self class];
id delegate = [UIApplication sharedApplication].delegate;
SEL selector = NSSelectorFromString(@"application:supportedInterfaceOrientationsForWindow:");
if ([delegate respondsToSelector:selector]) {
NSLog(@"respondsToSelector=YES");
//把方法加给原Class
class_addMethod(oldClass, newSEL, class_getMethodImplementation(newClass, newSEL), nil);
class_addMethod(oldClass, oldSEL, class_getMethodImplementation(newClass, defaultSEL),nil);
Method oldMethod = class_getInstanceMethod(oldClass, oldSEL);
assert(oldMethod);
Method newMethod = class_getInstanceMethod(oldClass, newSEL);
assert(newMethod);
method_exchangeImplementations(oldMethod, newMethod);
}else{
NSLog(@"AppDelegate未实现application:supportedInterfaceOrientationsForWindow:");
//此处强制添加实现的方法,我没加。有兴趣添加的麻烦评论区告诉我下。
}
}
-(UIInterfaceOrientationMask)defaultApplication:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
NSLog(@"defaultApplication");
return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft;
}
-(UIInterfaceOrientationMask)SDKApplication:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
NSLog(@"SDKDelegatesetAllowRotation");
return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft;
}