简体   繁体   中英

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.

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. 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. I am using the iphone5S as the simulator. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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