iOS屏幕旋轉控制的簡單實現,使用方式也非常簡單,需要控制旋轉的UIViewController遵守ShouldNotAutorotate協議即可,如:
MyUIViewController : UIViewController <ShouldNotAutorotate>
此方式適用于部分需要控制旋轉,而部分不需要控制旋轉的項目,有想法的自行修改。源碼
// UIViewController+ShouldNotAutorotate.h
#import <UIKit/UIKit.h>
/** 使用此協議的UIViewController不要重寫shouldAutorotate和supportedInterfaceOrientations方法,否則旋轉的控制就會失效 */
@protocol ShouldNotAutorotate @end
@interface UIViewController (ShouldNotAutorotate)
@end
// UIViewController+ShouldNotAutorotate.m
#import "UIViewController+ShouldNotAutorotate.h"
#import <objc/runtime.h>
@implementation UIViewController (ShouldNotAutorotate)
+ (void)load
{
Method sa = class_getInstanceMethod(self, @selector(shouldAutorotate));
Method xm_sa = class_getInstanceMethod(self, @selector(xm_shouldAutorotate));
method_exchangeImplementations(sa, xm_sa);
Method sio = class_getInstanceMethod(self, @selector(supportedInterfaceOrientations));
Method xm_sio = class_getInstanceMethod(self, @selector(xm_supportedInterfaceOrientations));
method_exchangeImplementations(sio, xm_sio);
}
- (BOOL)xm_shouldAutorotate
{
if ([self conformsToProtocol:@protocol(ShouldNotAutorotate)]) return NO;
return [self xm_shouldAutorotate];//返回原來的結果
}
- (UIInterfaceOrientationMask)xm_supportedInterfaceOrientations
{
if ([self conformsToProtocol:@protocol(ShouldNotAutorotate)]) return UIInterfaceOrientationMaskPortrait;
return [self xm_supportedInterfaceOrientations];//返回原來的結果
}
@end