參考鏈接:iOS屏幕旋
- 首先選擇支持的旋轉(zhuǎn)方向(兩種方法,推薦第二種)
(1)修改Info.plist文件跪削,見圖1
(2)直接上圖毫玖,(勾選即可)
2.在AppDelegate中添加屬性方法
在.h中添加一個(gè)屬性allowRotation
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property(nonatomic,assign)BOOL allowRotation;//是否允許轉(zhuǎn)向
@end
.m中添加下面的方法
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window{
if (_allowRotation == YES) {
return UIInterfaceOrientationMaskLandscapeRight;
}else{
return (UIInterfaceOrientationMaskPortrait);
}
}
3.在你需要旋轉(zhuǎn)的控制器.m中添加一下方法
- (void)setNewOrientation:(BOOL)fullscreen{
if (fullscreen) {
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}else{
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}
}
4.點(diǎn)擊旋轉(zhuǎn)按鈕調(diào)用- (void)setNewOrientation:(BOOL)fullscreen方法
//橫豎屏切換按鈕方法
-(void)screen{
//記著#import "AppDelegate.h"
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
if (_fullScreen ) {//橫屏情況下,點(diǎn)擊此按鈕變?yōu)樨Q屏
appDelegate.allowRotation = NO;//設(shè)置豎屏
[self setNewOrientation:NO];//調(diào)用轉(zhuǎn)屏代碼
self.navigationController.navigationBar.hidden = NO;//navbar消失
[self setViewFrame:NO];//豎屏布局
}else{//豎屏情況下,點(diǎn)擊此按鈕變?yōu)闄M屏
appDelegate.allowRotation = YES;////設(shè)置橫屏
[self setNewOrientation:YES];////調(diào)用轉(zhuǎn)屏代碼
self.navigationController.navigationBar.hidden = YES;//navbar出現(xiàn)
[self setViewFrame:YES];//橫屏布局
}
}