添加到窗口后自动调整 UIView 的大小 [英] Automatically Sizing UIView after Adding to Window

查看:20
本文介绍了添加到窗口后自动调整 UIView 的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这可能是 Subview 不自动调整大小的副本添加到根视图控制器时

我有一个 iPad 应用程序,可以在其主窗口中的不同视图之间切换.视图切换代码如下所示:

I have an iPad app that switches between different views in its main window. The view-switching code looks like this:

- (void)switchToViewController:(UIViewController*)viewController {
    if (currentViewController != viewController) {
        [currentViewController.view removeFromSuperview];
        currentViewController = viewController;
        [window addSubview:viewController.view];
    }
}

问题是当新视图(一个 UISplitView)横向出现时,它的大小没有填满整个窗口.右边有一大片空白的黑色空间.看起来视图只有 768 像素宽,而不是横向窗口的 1024 像素宽.

The problem is that when the new view (a UISplitView) appears in landscape orientation, it is not sized to fill the entire window. There is a large empty black space on the right. It looks like the view is only 768 pixels wide, rather than the 1024-pixel width of the landscape window.

如果我将设备旋转为纵向,然后再旋转回横向,则视图本身的大小会正确.

If I rotate the device to portrait and then back to landscape, the view sizes itself properly.

如果设备处于纵向,则一切正常.如果 UISplitView 是我显示的第一个视图,它的大小也会正确.仅当我在横向显示另一个视图后切换到它时才会出现此问题.

If the device is in portrait orientation, everything works fine. The UISplitView also gets sized properly if it is the first view I show. The problem only occurs if I switch to it after another view has been shown, in landscape.

那么,在将视图添加到窗口后,是否有某种方法可以强制 iPhone OS 调整视图大小?

So, is there some way to force iPhone OS to resize the view after it has been added to the window?

我试过调用 sizeToFitsetNeedsLayout.我还尝试将视图的 bounds 设置为窗口的 bounds,并且尝试设置 frame 以匹配前一个视图的框架.

I've tried calling sizeToFit, and setNeedsLayout. I've also tried setting the view's bounds to the window's bounds, and I've tried setting the frame to match the previous view's frame.

推荐答案

这可行,但似乎有点 hacky:

This works, but it seems a little hacky:

- (void)switchToViewController:(UIViewController *)viewController {
    if (viewController != currentViewController) {
        UIInterfaceOrientation orientation = currentViewController.interfaceOrientation;
        [currentViewController.view removeFromSuperview];

        currentViewController = viewController;
        UIView *view = viewController.view;

        // Set appropriate view frame (it won't be autosized by addSubview:)
        CGRect appFrame = [[UIScreen mainScreen] applicationFrame];
        if (UIInterfaceOrientationIsLandscape(orientation)) {
            // Need to flip the X-Y coordinates for landscape
            view.frame = CGRectMake(appFrame.origin.y, appFrame.origin.x, appFrame.size.height, appFrame.size.width);
        }
        else {
            view.frame = appFrame;
        }

        [window addSubview:view];
    }
}

这篇关于添加到窗口后自动调整 UIView 的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆