问题
I have a view that has been created in Interface Builder and configured to resize according to the orientation. If the view is created and added to the display while the application is in portrait mode everything works perfectly. I can then rotate the device/simulator and the view resizes as I would expect. But, if the view is added when the app is in landscape mode it does not resize correctly. The view is created and sized as if the app is still in portrait mode. The view is added with the following code:
self.viewController = [[MyViewController alloc] initWithNibName:nibName bundle:bundle];
[self addSubview:self.viewController.view];
Nothing magical happening here. Additionally, the view controller specifies:
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
Again, it works as expected as long as the view is added while in portrait mode. I've tried several different things including manually setting the autoresizingMask property on the view, calling setNeedsLayout, and calling layoutIfNeeded, but nothing seems to be working. I am able to manually set the width and height of the frame to force the view to resize, but this breaks the dynamic nature of the view. For example, if I manually set the width the height doesn't adjust as the content doesn't re-layout.
Any ideas?
回答1:
Just set your subview frame like this
self.viewController.view.frame = self.view.bounds;
回答2:
A quick answer here although I guess you will have solved this already :) The reason is because when you create and add the view, it is being loaded from the nib with the portrait frame. When loading, it isn't automatically rotated, because at that point the app can't know that you mean it to be rotated.
Some options include:
Have a Portrait and a Landscape nib, and load from the appropriate nib depending on current orientation when you add the view.
Adjust in code after loading as you had previously done.
There might be an option along the lines of forcing a relayout too, which sounds to me as though it is what you are after.
HTH
回答3:
I've just posted an answer to this on an almost identical question. Check out UIView addsubview after orientation change
回答4:
That is going to happen you are simply adding view of one view controller onto other. This is a bad practice and can lead to Internalinconsistency exception. See Container Api vedio from WWDC. For such thing containment api are used.
But you still want to do it this way. After adding view, you need to call shouldAutorotateToInterfaceOrientation on self.viewController
来源:https://stackoverflow.com/questions/5161894/when-adding-a-sub-view-the-view-does-not-resize-if-the-app-is-in-landscape-mode