【问题标题】:How to handle device orientation on multiple view in IOS7?如何在 IOS7 中处理多视图上的设备方向?
【发布时间】:2014-03-14 10:00:22
【问题描述】:
我正在开发一个应用程序,其中我有两个 ViewController 名称分别为 VC1 和 VC2,VC1 应该同时支持纵向和横向,这意味着纵向它应该显示地图,横向它应该显示列表。现在对于 VC2,它只能在纵向模式下工作。
我正在为两个 ViewControllers 附加图像
在第二张图片中,谷歌地图应该是纵向的,而列表是横向的,但是当我将方向从纵向更改为横向时,列表仅在纵向模式下生成。下面是处理方向的代码
- (BOOL)shouldAutorotate
{
return NO;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
【问题讨论】:
标签:
ios
iphone
objective-c
cocoa-touch
orientation
【解决方案1】:
如果您在应用程序中使用UINavigationController,-(BOOL)shouldAutorotate 将不会在您的 ViewControllers 中被调用。在这种情况下,您必须继承 UINavigationController。
@interface RotationAwareNavigationController : UINavigationController
@end
@implementation RotationAwareNavigationController
-(NSUInteger)supportedInterfaceOrientations {
UIViewController *top = self.topViewController;
return top.supportedInterfaceOrientations;
}
-(BOOL)shouldAutorotate {
UIViewController *top = self.topViewController;
return [top shouldAutorotate];
}
@end
【解决方案2】:
如果你的rootViewController 是UINavigationController,那么你需要使用UINavigationController 的类别。比如
UINavigationController+autoRotate.h
#import <UIKit/UIKit.h>
@interface UINavigationController (autoRotate)
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation;
-(BOOL)shouldAutorotate;
- (NSUInteger)supportedInterfaceOrientations;
@end
UINavigationController+autoRotate.m
#import "UINavigationController+autoRotate.h"
@implementation UINavigationController (autoRotate)
-(NSUInteger)supportedInterfaceOrientations
{
return [self.topViewController supportedInterfaceOrientations];
}
-(BOOL)shouldAutorotate
{
return self.topViewController.shouldAutorotate;
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return [self.topViewController shouldAutorotateToInterfaceOrientation:interfaceOrientation];
}
@end
然后在您的 viewController 中使用以下方法。
#pragma mark -
#pragma mark - UIInterfaceOrientation Methods
// for iOS 6 and latter
-(BOOL) shouldAutorotate
{
// return as you want;
return YES;
}
// for iOS 5 and lower
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// return as you want;
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
//UIInterfaceOrientationMask as you want
return UIInterfaceOrientationMaskPortrait;
}