Ios 旋转后的子viewcontroller高度为零
我一直在搜索,但找不到这个问题的答案。这似乎是相当基本的,所以希望有人能解释,或指向我以前的帖子 将viewcontroller的视图添加为另一个viewcontroller的子视图时,我发现子视图的“高度”属性在旋转时变为零。宽度也有增加的趋势 例如,在xib文件中将NSDChildViewController的视图设置为50x100时Ios 旋转后的子viewcontroller高度为零,ios,rotation,viewcontroller,Ios,Rotation,Viewcontroller,我一直在搜索,但找不到这个问题的答案。这似乎是相当基本的,所以希望有人能解释,或指向我以前的帖子 将viewcontroller的视图添加为另一个viewcontroller的子视图时,我发现子视图的“高度”属性在旋转时变为零。宽度也有增加的趋势 例如,在xib文件中将NSDChildViewController的视图设置为50x100时 @implementation ParentViewController -(void)viewDidLoad { [super viewDidLoad
@implementation ParentViewController
-(void)viewDidLoad
{
[super viewDidLoad];
mChild = [[ChildViewController alloc] initWithNibName:nil
bundle:nil];
[self.view addSubview:mChild.view];
}
-(void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
[mChild printFrame];
}
@end
@implementation ChildViewController
-(void)printFrame
{
NSLog(@"%s %@",__FUNCTION__, NSStringFromCGRect(self.view.frame));
}
@end
各方向纵向->横向->纵向的日志记录如下:
-[ChildViewController打印框]{{0,0},{50,100}
-[ChildViewController打印框]{{0,0},{298,0}
-[ChildViewController打印框]{{0,0},{50248}
为什么会发生这种情况?我该如何预防?目前,在尝试以编程方式将ViewController布局为子视图时,它给我带来了麻烦。到目前为止,我找到的唯一解决方案是使用类似这样的方法将size属性强制返回到50x100
-(void)forceSize
{
CGRect frame = self.view.frame;
frame.size.width=50;
frame.size.height=100;
self.view.frame=frame;
}
但上述情况似乎很可笑。非常感谢您的帮助。当父视图的框架发生变化时,它会自动调整子视图的大小。在这种情况下,当设备在纵向和横向模式之间切换时,父视图的帧会发生变化 您似乎正在4英寸iPhone设备(或模拟器)上进行测试,因此我们使用的尺寸是:320 x 568。父视图将用尽屏幕的全部宽度和高度 下面是正在发生的事情: 从纵向旋转到横向之前:
widthDifference = parentViewWidth - originalChildViewWidth // 270 (320 - 50)
heightDifference = parentViewHeight - originalChildViewHeight // 468 (568 - 100)
childLandscapeViewWidth = parentViewHeight - widthDifference // 298 (568 - 270)
childLandscapeViewHeight = parentViewWidth - heightDifference // -148 (320 - 468)
// (but height cannot be < 0, so this is automatically set to 0)
从纵向旋转到横向后:
widthDifference = parentViewWidth - originalChildViewWidth // 270 (320 - 50)
heightDifference = parentViewHeight - originalChildViewHeight // 468 (568 - 100)
childLandscapeViewWidth = parentViewHeight - widthDifference // 298 (568 - 270)
childLandscapeViewHeight = parentViewWidth - heightDifference // -148 (320 - 468)
// (but height cannot be < 0, so this is automatically set to 0)
从横向旋转到纵向后:
widthDifference = parentViewWidth - childLandscapeViewWidth // 270 (568 - 298)
heightDifference = parentViewHeight - childLandscapeViewHeight // 320 (320 - 0)
childPortraitViewWidth = parentViewWidth - widthDifference // 50 (320 - 270)
childPortraitViewHeight = parentViewHeight - heightDifference // 248 (568 - 320)
最终我们得到了子视图的宽度=50,高度=248
因此,要停止这种疯狂行为,请将父视图()上的autoresizesSubviews
设置为NO
,如下所示:
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.autoresizesSubviews = NO;
...
}
就这样!感谢您花时间编写一个清晰的解决方案。一旦我有足够的声誉,我会投票支持你的回答;)没问题。同时,你能接受这个正确答案吗?