步驟和代碼
- 第一步 :Appdelegate文件中設(shè)置
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
//在AppDelegate.h文件中設(shè)置兩個(gè)屬性
@property(nonatomic, assign) BOOL isForcePortrait;
@property(nonatomic, assign) BOOL isForceLandscape;
@end
//在AppDelegate.m文件中實(shí)現(xiàn)代理方法
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
if (self.isForceLandscape) {
return UIInterfaceOrientationMaskLandscape;
}else if (self.isForcePortrait){
return UIInterfaceOrientationMaskPortrait;
}else{
return UIInterfaceOrientationMaskAll;
}
}
- 第二步:設(shè)置橫豎屏的方法矿辽,寫(xiě)在分類中
//UIDevice+TFDevice.h文件
#import <UIKit/UIKit.h>
@interface UIDevice (TFDevice)
//interfaceOrientation 輸入要強(qiáng)制轉(zhuǎn)屏的方向
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation;
@end
//UIDevice+TFDevice.m文件
#import "UIDevice+TFDevice.h"
@implementation UIDevice (TFDevice)
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation
{
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:interfaceOrientation];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}
@end
- 第三步:設(shè)置橫豎屏
#pragma mark - 強(qiáng)制橫豎屏設(shè)置
- (void)forceOrientationLandscape { //強(qiáng)制橫屏
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.isForcePortrait = NO;
appDelegate.isForceLandscape = YES;
[UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];
}
- (void)forceOrientationPortrait { //強(qiáng)制豎屏
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.isForcePortrait = YES;
appDelegate.isForceLandscape = NO;
[UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
}
注意
這個(gè)在展示控制器的時(shí)候需要調(diào)用秋泳,在dismiss或者pop掉控制器的時(shí)候也需要將設(shè)置恢復(fù)原樣益兄。
在第三步上強(qiáng)制橫屏的以下這句代碼中卡儒,后面的旋轉(zhuǎn)方向僅僅是告訴屏幕要往橫屏右方向轉(zhuǎn)蛆橡,至于轉(zhuǎn)完之后屏幕能不能也能橫屏左那就要看Appdelegate里面實(shí)現(xiàn)的代理方法怎么實(shí)現(xiàn)的了...
[UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];
參考
以上9鞍蟆!九妈!
彈鋼琴.gif