5

可能重复:
在 iPhone 中重新定向后“不正确”的框架/窗口大小

我正在尝试用我的应用程序解决一个非常令人沮丧的问题 - 在研究它时,我可能在 iOS 中发现了一个错误:

当您旋转 iPad 时,视图会旋转,但它的框架不会改变。我正在运行一个计时器,它每秒打印出我的视图的宽度和高度,虽然我可以看到视图在视觉上旋转,但无论如何框架仍然是“768x1024”。

来自 Apple 的文档:

当用户界面旋转时,窗口会调整大小以匹配新方向。窗口调整其根视图控制器的框架以匹配新的大小,而这个大小又会沿着视图层次向下传播到其他视图。

这正是没有发生的事情,它给我带来了各种各样的麻烦。有谁知道如何修复旋转以使框架发生变化?

重现步骤:

  1. 创建一个新的空项目
  2. 添加骨骼 UIViewController 作为根视图
  3. 设置一个计时器来打印出根视图控制器的框架宽度和高度
  4. 运行您的应用程序,并旋转它。这是我正在测试的代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = [[UIViewController alloc] init];

    NSLog(@"%fx%f", self.window.rootViewController.view.frame.size.width, self.window.rootViewController.view.frame.size.height);

    // 添加标签以确认方向
    UILabel *orientationLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,10,100,30)];
    orientationLabel.text = @"左上角";
    [self.window.rootViewController.view addSubview:orientationLabel];

    [NSTimer scheduleTimerWithTimeInterval:.3 target:self 选择器:@selector(testScale) userInfo:nil repeats:YES];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    返回是;
}
-(无效)testScale {
    NSLog(@"%fx%f", self.window.rootViewController.view.frame.size.width, self.window.rootViewController.view.frame.size.height);
}
4

3 回答 3

1

您是否尝试将 UIViewController 放在 UINavigationController 中?我有一个类似的问题,它解决了它。UINavigationController 类似乎比 UIViewController 处理更好的旋转。

尝试这样的事情:

UIViewController *myViewController = [[UIViewController alloc] init];
UINavigationController *myNavigationController = [[UINavigationController alloc] initWithRootViewController:myViewController];
self.window.rootViewController = myNavigationController;
于 2012-11-08T21:37:34.103 回答
0

不是错误。你想要的是使用bounds而不是frame

这样想吧。旋转设备时,设备不会更改其屏幕尺寸。它保持不变,但观点正在改变。所以这就是你想要使用边界的原因。

于 2012-11-08T21:17:14.433 回答
0

您可以使用状态栏的状态

 [[UIApplication sharedApplication] statusBarOrientation]

使用if 语句,您可以知道屏幕是横向还是纵向

于 2012-11-08T21:27:47.617 回答