简体   繁体   English

如何在父uiview中设置uiview大小?

[英]how to set the uiview size inside of a parent uiview?

I used the following code to set a child UIView (a white box) inside of a UIView. 我使用以下代码在UIView中设置了子UIView(白框)。

float x = 10.0;
float y = 40.0;
float w = self.view.frame.size.width - 20.0f;
float h = self.view.frame.size.height/3.0;
UIView *whiteBox = [[UIView alloc] initWithFrame:CGRectMake(x, y, w, h)];

Basically, I want to draw a white box with 10-pixel to the both margins of the parent UIView. 基本上,我想在父UIView的两个边距处绘制一个10像素的白框。 However, The right side of the white box is always beyond the parent view's boundary. 但是,白框的右侧始终超出父视图的边界。 It looks like the self.view.frame.size.width is larger than the actual view's width. 看起来self.view.frame.size.width大于实际视图的宽度。 I am using the iphone5S as the simulator. 我正在使用iphone5S作为模拟器。 I just want to know how I can set the correct width of the white box. 我只想知道如何设置白色框的正确宽度。

In what method are you doing this? 您以哪种方法进行此操作? You may be getting a value for the parent view's width from storyboard before it has a chance to resize and fit the screen. 您可能会从情节提要中获取父视图的宽度值,然后才有机会调整其大小并适合屏幕。

To avoid issues like this, it's always best to use autolayout instead of providing these types of calculations which are error prone and take time to read. 为避免出现此类问题,始终最好使用自动布局,而不是提供容易出错且读取时间较长的这些类型的计算。 If you can, add the uiview in storyboard, and add leading, trailing, top, and bottom constraints to superview with constants equal to 10. 如果可以,请在情节提要中添加uiview,并在常量等于10的superview中添加前导,尾随,顶部和底部约束。

您可以使用左边界和右边界之类的约束,以便视图相对于其父视图自动进行调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM