0

在我的根视图控制器的 viewDidLoad 中,我添加了一个用于方向检测的观察者:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willRotateToInterfaceOrientation:duration:) name:@"UIDeviceOrientationDidChangeNotification" object:nil]; 

添加了如下方法:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                                duration:(NSTimeInterval)duration {
    NSLog(@"%f,%f",self.view.frame.size.width,self.view.frame.size.height);
}

我期待纵向的结果为 768,1004,横向的结果为 1004,768。但我的结果是两者都是 768,1004。有时,肖像会是 748,1024。我不知道为什么会出现这种奇怪的行为。如果您知道解决方案,请帮助我。

编辑 这个相同的代码在我的另一个项目中工作,我找不到它们之间的任何区别

4

3 回答 3

1

添加这两个方法:

- (BOOL)shouldAutorotate
{
      return TRUE;
}

- (NSUInteger)supportedInterfaceOrientations
{
     return UIInterfaceOrientationMaskAll;
}

并在此处进行所有修改:

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)  interfaceOrientation duration:(NSTimeInterval)duration
{
     NSLog(@"%f,%f",self.view.frame.size.width,self.view.frame.size.height);
}  
于 2013-08-02T04:44:54.700 回答
0

首先,您不需要为该通知添加观察者,默认情况下会向视图控制器发送此通知。因此,删除前两行,它应该可以正常工作。而且由于这是“意志”方法,因此正确地意味着您在旋转之前获得了视图的大小。

但是,方法 willAnimateRotationToInterfaceOrientation:duration: 确实会在旋转后为您提供视图的尺寸,如果这是您想要的(即使它是“意志”方法)。

编辑后

由于某种原因,这些方法对于嵌入在导航控制器中的控制器可以正常工作,但不适用于单个控制器或模态控制器。对于这些情况,从帧的边界切换可以解决问题。

于 2013-08-02T04:48:56.373 回答
0

[如果您查看 Apple 的文档willRotateToInterfaceOrientation,它会说]:

在用户界面开始旋转之前发送到视图控制器。

这意味着框架的宽度和高度应该是旋转的方向。

也许如果您尝试在旋转完成后获取框架坐标,例如,在 期间didRotateFromInterfaceOrientation,您可能会看到更像您希望完成的东西。

于 2013-08-02T04:43:48.593 回答