I am trying to add a subview to a UIScrollView. First I instantiate the view controller from the storyboard, then set the view's frame to the application bounds. When I add the view to the UIScrollView, it is clearly larger than it's supposed to be.
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 is extending past where it should be. "Debug View Hierarchy" mode in XCode also confirms this. But, if I inspect the view's frame, it prints out what it should be, not what it actually is.
A view of the same size, but generated completely programatically, works as it should:
mainView = [[UIView alloc] initWithFrame:mainFrame];
mainView.backgroundColor = [UIColor blackColor];
[self.scrollView addSubview:mainView];
I'm not sure what could be causing this issue - I've instantiated other views from their view controllers, also via the storyboard, and set their frames without any problems.
EDIT: This is being called from viewDidLoad of the view controller containing the UIScrollView. screenWidth & screenHeight are calculated as such (they are instance variables):
screenWidth = [UIScreen mainScreen].applicationFrame.size.width;
screenHeight = [UIScreen mainScreen].applicationFrame.size.height;
Try to set the view frame in viewWillAppear
method.
viewDidLoad
is not a good place to set frames (because it called only once when view getting loaded.), the UI components are not properly configured by the system yet.
Also, prefer to use:
screenWidth = [UIScreen mainScreen].bounds.size.width;
screenHeight = [UIScreen mainScreen].bounds.size.height;
instead of
screenWidth = [UIScreen mainScreen].applicationFrame.size.width;
screenHeight = [UIScreen mainScreen].applicationFrame.size.height;
since bounds has correct positional information taking into consideration the device's orientation in this case.
Or you can just do this, after initializing the mainView inside viewDidLoad:
Method
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
mainView.frame = [UIScreen mainScreen].bounds;
}
you can also add this to reconfigure the view frame whenever the subviews are updated:
- (void)viewWillLayoutSubviews { //or viewDidLayoutSubviews
[super viewWillLayoutSubviews];
mainView.frame = [UIScreen mainScreen].bounds;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With