29

我正在向我的应用程序添加一个额外的 UIWindow。我的主窗口可以正确旋转,但我添加的这个附加窗口没有旋转。

根据当前设备方向旋转 UIWindow 的最佳方法是什么?

4

5 回答 5

45

你需要为 UIWindow 滚动你自己的。

监听UIApplicationDidChangeStatusBarFrameNotification通知,然后在状态栏更改时设置转换。

您可以从 读取当前方向-[UIApplication statusBarOrientation],并计算如下变换:

#define DegreesToRadians(degrees) (degrees * M_PI / 180)

- (CGAffineTransform)transformForOrientation:(UIInterfaceOrientation)orientation {

    switch (orientation) {

        case UIInterfaceOrientationLandscapeLeft:
            return CGAffineTransformMakeRotation(-DegreesToRadians(90));

        case UIInterfaceOrientationLandscapeRight:
            return CGAffineTransformMakeRotation(DegreesToRadians(90));

        case UIInterfaceOrientationPortraitUpsideDown:
            return CGAffineTransformMakeRotation(DegreesToRadians(180));

        case UIInterfaceOrientationPortrait:
        default:
            return CGAffineTransformMakeRotation(DegreesToRadians(0));
    }
}

- (void)statusBarDidChangeFrame:(NSNotification *)notification {

    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

    [self setTransform:[self transformForOrientation:orientation]];

}

根据您的窗口大小,您可能还需要更新框架。

于 2011-07-14T18:23:31.550 回答
16

只需创建一个UIViewController自己的UIView,将其分配rootViewController给您的窗口并将所有进一步的 UI 添加到控制器的视图(而不是直接添加到窗口),控制器将为您处理所有旋转:

UIApplication * app = [UIApplication sharedApplication];
UIWindow * appWindow = app.delegate.window;

UIWindow * newWindow = [[UIWindow alloc] initWithFrame:appWindow.frame];
UIView * newView = [[UIView alloc] initWithFrame:appWindow.frame];
UIViewController * viewctrl = [[UIViewController alloc] init];

viewctrl.view = newView;
newWindow.rootViewController = viewctrl;

// Now add all your UI elements to newView, not newWindow.
// viewctrl takes care of all device rotations for you.

[newWindow makeKeyAndVisible];
// Or just newWindow.hidden = NO if it shall not become key

当然,同样的设置也可以在界面构建器中创建,而无需单行代码(除了在显示窗口之前将框架大小设置为填满整个屏幕)。

于 2014-12-02T16:01:15.047 回答
4

您需要设置新窗口的 rootViewController。然后窗口的子视图将正确旋转。

myNewWindow!.rootViewController = self

然后您可以在旋转方法中更改帧。

例如(在 ios8 中为 swift)

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { customAlertView.frame = UIScreen.mainScreen().bounds }

于 2015-03-30T03:37:36.017 回答
1

我不知道你对窗户做了什么。但是根控制器需要以 YES 响应 shouldAutorotate。

于 2011-07-14T18:13:32.020 回答
1

你可以为你的 UIWindow 设置 rootController。例如:

fileprivate(set) var bottonOverlayWindow = UIWindow()

self.bottonOverlayWindow.rootViewController = self; 

// 'self' 将是您在其上添加 UIWindow 视图的 ViewController。所以每当你 ViewController 改变方向时,你的窗口视图也会改变它的方向。

如果您遇到任何问题,请告诉我。

于 2019-09-13T12:25:00.417 回答