UIView在方向更改后添加子视图:告诉视图调整大小

mar*_*mba 7 iphone orientation addsubview autoresizingmask

我在肖像模式下有一个UIView作为XIB.

此视图以编程方式添加到viewcontroller,如下所示:

NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"InputView" owner:self options:nil];
    InputView *inputView = (InputView*)[nibObjects objectAtIndex:0];
    [self.view addSubview:inputView];
Run Code Online (Sandbox Code Playgroud)

此视图具有正确设置的自动调整遮罩,并且在方向从纵向更改为横向时旋转正常.

但是,如果方向已经是横向,并且我在方向更改创建视图,则它具有其初始纵向方向.

有没有办法告诉视图使用其掩码初始化或自己调整为肖像?

在此先感谢您的回复!

编辑:使用occulus和Inder Kumar Rathore的建议(谢谢你们!),我将代码改为:

InputView *inputView = (InputView*)[nibObjects objectAtIndex:0];
[self.view addSubview:inputView];
[self.view setNeedsLayout];
[self.view layoutSubviews];
[self.view layoutIfNeeded];
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
[self shouldAutorotateToInterfaceOrientation:orientation];
Run Code Online (Sandbox Code Playgroud)

不幸的是,根本没有变化.我想我发现有人问同样的问题:

添加子视图时,如果应用程序处于横向模式,则视图不会调整大小

答案正确地确定了问题,但并不是非常令人鼓舞......当然,我可以创建两个笔尖或调整框架大小,但这似乎与自动调整大小的想法相反.我觉得很难相信在唤醒之后无法告诉笔尖并将其添加到视图中以使用其自动调整功能......当设备旋转时它会完美无瑕.

编辑2:

idz的解决方案有效:

InputView *inputView = (InputView*)[nibObjects objectAtIndex:0];
[self.view addSubview:inputView];
inputView.frame = self.view.bounds;
[inputView show];
Run Code Online (Sandbox Code Playgroud)

谢谢!

idz*_*idz 19

通常,NIB/XIB文件包含一个UIViewController负责所有这一切的文件.在这种情况下,由于它们不是视图控制器(在NIB/XIB中),因此您需要接管其后载任务.

layoutSubviews直接调用,或间接调用setNeedsLayoutlayoutIfNeeded不会对您有好处,因为默认实现不执行任何操作.

假设您希望输入视图填充self.view的边界,请执行以下操作:

InputView *inputView = (InputView*)[nibObjects objectAtIndex:0];
[self.view addSubview:inputView];
inputView.frame = self.view.bounds;
[inputView show];
Run Code Online (Sandbox Code Playgroud)

必须正确设置子视图的所有调整大小掩码才能使其正常工作,显然,如果您不想填充整个边界,则可能需要调整帧.