Rendering a UIView frame larger than a frame
I am trying to add subview to UIScrollView. First, I instantiate the view controller from the storyboard and then set the view frame to the app bounds. When I add the view to the UIScrollView, it is clearly larger than intended.
CGRect mainFrame = CGRectMake(0, topButtonHeight, screenWidth, screenHeight);
feelingVC = (FeelingViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"feelingVC"];
feelingVC.delegate = self;
feelingView = feelingVC.view;
[feelingView setFrame:mainFrame];
[self.scrollView addSubview:feelingView];
I can tell because its background color goes further where it should be. It also confirms the "Initialize Debug Mode" mode in Xcode. But, if I check the frame of the view, it prints what it should be, not what it actually is.
A view of the same size, but generated entirely programmatically, works as it should:
mainView = [[UIView alloc] initWithFrame:mainFrame];
mainView.backgroundColor = [UIColor blackColor];
[self.scrollView addSubview:mainView];
I'm not sure what might be causing this problem. I created other views from my view controllers, also through storyboard, and set my frames without issue.
EDIT: It is called from the viewDidLoad of the view controller containing the UIScrollView. screenWidth and screenHeight are calculated as such (they are instance variables):
screenWidth = [UIScreen mainScreen].applicationFrame.size.width;
screenHeight = [UIScreen mainScreen].applicationFrame.size.height;
Try setting the view frame to viewWillAppear
.
viewDidLoad
is not a good place to set frames (because it was only called once when the view was loaded.) The UI components are not configured by the system yet.
Also, prefer to use:
screenWidth = [UIScreen mainScreen].bounds.size.width;
screenHeight = [UIScreen mainScreen].bounds.size.height;
instead
screenWidth = [UIScreen mainScreen].applicationFrame.size.width;
screenHeight = [UIScreen mainScreen].applicationFrame.size.height;
because the boundaries have the correct positional information, taking into account the orientation of the device in this case.
Or you can just do this after initializing mainView inside viewDidLoad:
Method
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
mainView.frame = [UIScreen mainScreen].bounds;
}
you can also add this to re-adjust the view frame whenever the subview is updated:
- (void)viewWillLayoutSubviews { //or viewDidLayoutSubviews
[super viewWillLayoutSubviews];
mainView.frame = [UIScreen mainScreen].bounds;
}