0

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.

mmjuns
  • 177
  • 1
  • 11

2 Answers2

0

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.

Josh Gafni
  • 2,831
  • 2
  • 19
  • 32
  • The width is 600 and it's in the ViewDidLoad method. Yes, I can use the auto layout in the storyboard which I am already done. I am just curious about how to achieve this in the code. Of course, I can still use auto layout constraints programmingly. I just want to know why it looks like the uiview's frame width is not right for my current simulator (Iphone5S). – mmjuns Mar 23 '16 at 16:44
  • `ViewDidLoad` is your problem. The frame is not set up after this method. Try moving it to `ViewWillAppear:` or `ViewDIdAppear:` See http://stackoverflow.com/questions/6757018/why-am-i-having-to-manually-set-my-views-frame-in-viewdidload for more info. – Josh Gafni Mar 23 '16 at 16:49
0

you can use the constraint like left margin and right margin so that the view will adjust itself automatically with respect to its superview.

Ujjwal Khatri
  • 716
  • 1
  • 6
  • 19
  • Yes. I have done this. Just want to know why my code doesn't work correctly. It seems the width is not right for my current simulator. – mmjuns Mar 23 '16 at 16:45