iOS 屏幕旋转 nav+tabbar+present(网页) 2016

时间:2022-08-31 15:07:57

如题,最近一个app架构为 nav + tabbar ,需求是 在点击tabbar中的一个菜单项时,弹出网页,该网页需要横屏显示,其他页面不变  都保持竖屏。

XCode Version 7.2.1

网上一搜,都说到在nav或者tabbar中设置以下3个方法。

-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait ;
}
- (BOOL)shouldAutorotate
{
return NO;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}

确实实现了横屏的需求,但是发现了一个bug:

当app在横屏的时候 运行app  界面就是横屏了,虽然进入关闭网页时可以显示回正常竖屏,但是。。。。

最终 参考了一个老外的做法。传送门

该实现方式主要代码为:在AppDelegate中添加以下方法

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
// Get topmost/visible view controller
UIViewController *currentViewController = [self topViewController]; // Check whether it implements a dummy methods called canRotate
if ([currentViewController respondsToSelector:@selector(canRotate)]) {
// Unlock landscape view orientations for this view controller if ([currentViewController isKindOfClass:[ViewController1 class]]) {
if(((ViewController1 *)currentViewController).isShowPortrai){
return UIInterfaceOrientationMaskPortrait;
}else{
return UIInterfaceOrientationMaskLandscapeRight;
}
}
return UIInterfaceOrientationMaskLandscapeRight;
} // Only allow portrait (standard behaviour)
return UIInterfaceOrientationMaskPortrait;
} - (UIViewController*)topViewController {
return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
} - (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
if ([rootViewController isKindOfClass:[UITabBarController class]]) {
UITabBarController* tabBarController = (UITabBarController*)rootViewController;
return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
} else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
UINavigationController* navigationController = (UINavigationController*)rootViewController;
return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
} else if (rootViewController.presentedViewController) {
UIViewController* presentedViewController = rootViewController.presentedViewController;
return [self topViewControllerWithRootViewController:presentedViewController];
} else {
return rootViewController;
} }

其中改造部分为:

if(((ViewController1 *)currentViewController).isShowPortrai){
return UIInterfaceOrientationMaskPortrait;
}else{
return UIInterfaceOrientationMaskLandscapeRight;
}

完美实现此效果:进入app时竖屏,进入网页时横屏,关闭网页时返回竖屏。 特此记录

注:只需在项目中设置下图(默认设置),参考demo实现即可。 其中左右旋转看需求设置

iOS 屏幕旋转 nav+tabbar+present(网页) 2016

demo地址