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

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

问题描述

注意:这可能与 Subview Doesnt AutoSize重复添加到根视图控制器时

我有一个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?

我尝试调用 sizeToFit setNeedsLayout 。我也尝试将视图的界限设置为窗口的界限,我尝试设置 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天全站免登陆