2014-10-10 67 views
0

我正在尝试将子视图添加到现有视图。我基本上是添加子视图模仿ActionSheet这样的例子:在iOS应用中添加自动布局子视图时的高度错误

http://cocoaallocinit.com/2014/03/23/implementing-a-custom-uiactionsheet

这个例子很好,只要我不上的自定义ActionSheet使用自动布局工作。当我这样做时,我会遇到一些问题。我添加的子视图由一个红色视图组成。这个红色视图对其高度,水平和垂直空间都有限制。

xib

我的问题是高度似乎并没有放在4S和5S设备正确。 5S的视角比4S更高。我预计这是相反的,因为5S比4S有更多的积分。

Side by side

我添加子视图与此代码:

[self.view addSubview:self.customActionSheet.view]; [self.customActionSheet viewWillAppear:NO];

如果我不是推它添加视图:

[self.navigationController pushViewController:self.customActionSheet animated:YES];

那么结果就是像我期望。 4S完全被红色视图覆盖,5S仍然在红色视图上方有一些区域。

我在这里做错了什么?

+0

是您使用自动布局或自动调整 – 2014-10-10 12:53:22

回答

1

您的视图不会根据设备屏幕自动调整大小。 [UINavigationController pushViewController: animated:]将工作,因为导航控制器为您设置视图的框架。快速的方法是使用当前视图设置视图的框架。

self.customActionSheet.view.frame = self.view.bounds; 

而你自己不要调用viewWillAppear:,系统会调用它。

我的建议是使用自动布局来完成您的视图到超视图。下面的代码使用PureLayout:https://github.com/smileyborg/PureLayout

[self.view addSubview:self.customActionSheet.view] 
[self.customActionSheet.view autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero]; 
0

的问题是,你需要添加约束self.customActionSheet.view

当您通过pushViewController:animated:消息加载控制器视图时,系统添加视图所需的约束,以填充所有屏幕空间。如果您手动添加它(通过addSubview:消息),则不会自动创建自动布局约束,并且您需要创建并以编程方式将它们添加到视图中。

我张贴在这里,你可能需要的东西,所以你customActionSheet填满所有的屏幕空间的例子:

NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:self.view 
                     attribute:NSLayoutAttributeLeft 
                     relatedBy:NSLayoutRelationEqual 
                     toItem:self.customActionSheet.view 
                     attribute:NSLayoutAttributeLeft 
                    multiplier:1.0 
                     constant:0]; 

NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:self.view 
                     attribute:NSLayoutAttributeTop 
                     relatedBy:NSLayoutRelationEqual 
                     toItem:self.customActionSheet.view 
                     attribute:NSLayoutAttributeTop 
                    multiplier:1.0 
                     constant:0]; 

NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:self.view 
                     attribute:NSLayoutAttributeBottom 
                     relatedBy:NSLayoutRelationEqual 
                     toItem:self.customActionSheet.view 
                     attribute:NSLayoutAttributeBottom 
                    multiplier:1.0 
                     constant:0]; 


NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:self.view 
                    attribute:NSLayoutAttributeRight 
                    relatedBy:NSLayoutRelationEqual 
                    toItem:self.customActionSheet.view 
                    attribute:NSLayoutAttributeRight 
                   multiplier:1.0 
                    constant:0]; 

[self.view addSubview:self.customActionSheet.view]; 
[self.view addConstraints:@[left, right, top, bottom]]; 
+0

约束在厦门国际银行文件已经添加。对不起,没有解释。 – Espen 2014-10-10 14:12:34

相关问题