2013-10-04 28 views
1

有这个问题已经有几个问题,但没有一个满意的答案。我想知道为什么框架和边界看起来是错误的,使用最简单的可能的例子,并且有人告诉我什么是正确的方法来处理它...UIViewController/UIView方向框/界限在风景只有应用程序

我使单一视图应用程序,没有故事板,我只勾选景观支持。然后在didFinishLaunching方法:


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 

    ViewController *vc = [[ViewController alloc] init]; 
    self.window.rootViewController = vc; 
    [self.window makeKeyAndVisible]; 

    return YES; 
} 

,并在视图控制器:


- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.view.backgroundColor = [UIColor redColor]; 
} 

- (void)viewDidAppear:(BOOL)animated 
{ 
    NSLog(@"%.1f,%.1f",self.view.frame.size.width,self.view.frame.size.height); 
} 

则输出768.0,1024.0 - 这显然是错误的,即使红色充满了景观尺寸屏幕。所以我不能依靠self.view.frame或self.view.bounds来排列或调整子视图的大小。

什么是最新的“适当的”方法来避免这样的问题? (没有使用笔尖或故事板,也没有hacky交换宽度和高度)

+0

试试这个的NSLog(@ “%@”,self.view);它会给yiu框架 – Purva

+1

它不是nslog的问题,记录整个视图对象确认了同样的问题:> – jonydep

回答

0

不知道这是否正确,但这是我最好的猜测,我现在无法测试。如果我没有错,默认方向是任何应用程序的纵向。所以,为了支持不同的方向,你的应用程序应该实现自动旋转方法(根据你构建的iOS版本有所不同)。因此,即使您的应用程序被勾选为仅支持横向模式,它也不会实际旋转。尝试执行指定的方法,让我知道如何去...

为iOS 5和更早版本,你应该使用:

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation 
{ 
if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) 
{ 
return YES; 
} 

return NO; 
} 

适用于iOS 6,以后你应该使用:

-(NSUInteger)supportedInterfaceOrientations 
{ 
return UIInterfaceOrientationMaskLandscape; 
} 

-(BOOL)shouldAutorotate 
{ 
return YES; 
} 

如果在旋转发生后检查视图的框架,它应该是好的。

编辑:

看看this SO question和它的答案。他们提供了一些很好的解决方法。此外,鉴于在应用程序中,您将主要将视图控制器嵌入到导航控制器或选项卡栏控制器中,或者甚至两者中,您可以继续并在其上创建子类别以确保将所有内容都转发给您的视图控制器。

另一个great answer解释了实际发生的事情。

+0

didRotateFromInterfaceOrientation似乎并没有被调用,所以我不知道如何检查后旋转。顺便说一句,我认为你的supportInterfaceOrientations返回值应该是UIInterfaceOrientationMaskLandscape – jonydep

+0

@jonydep它确实被调用。我自己测试了一下。是的,你使用UIInterfaceOrientationMaskLandscape是正确的。另请参阅更新 –

0

您正在检查帧和边界的大小太快。

相反,检查它们旋转后:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { 
    NSLog(@"Bounds %@", NSStringFromCGRect(self.view.bounds)); 
    NSLog(@"Frame %@", NSStringFromCGRect(self.view.frame)); 
} 
+0

这看起来似乎是文档中建议的内容,但是根本没有调用RotateFromInterfaceOrientation。 – jonydep

相关问题