项目需求:
1 竖屏状态,想在 present 的时候为横屏
2 横屏状态, present的时候 为竖屏状态.
我只是以第一个需求为例,第二种情况,道理相同。
1.gif
- 无需强行选中 Device Orientation 中的 Portrait 选项 如图1,当然选中也是可以的。
2.在appdelegate 中设置标识符,或者枚举类型,判断当前屏幕支持的屏幕 orientation 方向。
// AppDelegate.h
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, ViewDirection) {
ViewDirectionAll = 0,
ViewDirectionLandscape,
ViewDirectionPortrait,
};
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic,assign) ViewDirection viewDirection;
@end
然后在.m文件中
// AppDelegate.m
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
if (self.viewDirection == ViewDirectionAll){
return UIInterfaceOrientationMaskAllButUpsideDown;
} else if (self.viewDirection == ViewDirectionLandscape){
return UIInterfaceOrientationMaskLandscape;
} else if ( self.viewDirection == ViewDirectionPortrait) {
return UIInterfaceOrientationMaskPortrait;
} else {
return UIInterfaceOrientationMaskPortrait;
}
}
3 .1先实现 present 部分, 如果是跳转到 navigationController 的rootViewController 中 需要在自定义navigationController 在.m中添加如下代码
// @interface NavViewController : UINavigationController
// NavViewController.m
- (BOOL)shouldAutorotate{
return NO;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskLandscape;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
// return UIInterfaceOrientationPortrait;
return UIInterfaceOrientationLandscapeLeft|UIDeviceOrientationLandscapeRight;
}
3.2 跳转实现。
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
WebViewController *webVC = [[WebViewController alloc] initWithNibName:NSStringFromClass([WebViewController class]) bundle:nil];
NavViewController * nav = [[NavViewController alloc] initWithRootViewController:webVC];
[self presentViewController:nav animated:YES completion:nil];
}
4 特殊问题,如果 是横屏状态 用到alertviewcontroller
时。会crash
。解决办法,写一个分类.
#import "UIAlertController+MMAlertController.h"
@implementation UIAlertController (MMAlertController)
- (BOOL)shouldAutorotate{
return NO;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return UIInterfaceOrientationPortrait;
}
@end
5 特殊问题2,如果是横屏状态,跳转到竖屏状态,而竖屏又push 到另一个vc中,一定要在另一个vc中重写 上三方法。不然会导致 status bar
横过来。
网友评论