Reputation: 42139
I created a separate .xib because I wanted to design a UIView
with autolayout
outside of a viewController. I created the .xib, added the UIView
and the constraints, using wCompact hRegular
. Simple.
Then add it to my viewController
in viewDidLoad
:
UIView *header = [[[NSBundle mainBundle] loadNibNamed:@"HeaderSearch" owner:self options:nil] lastObject];
NSLog(@"%@", NSStringFromCGRect(header.frame));
[self.view addSubview:header];
But, when it is added, the frame size is 600x600 and I cannot figure out why.
What have I done wrong here that is forcing this strange size?
Upvotes: 14
Views: 6680
Reputation: 12303
I think, this is the best of correct ways:
- (void)willMoveToParentViewController:(UIViewController *)parent {
[super willMoveToParentViewController:parent];
self.view.frame = parent.view.frame;
[self.view layoutIfNeeded];
// adjust subviews here
}
View will get correct frame and adjustments will called only once on initialization.
Upvotes: 0
Reputation: 1409
I had a similar problem but in my case I didn't like to turn off trait variations or size classes. I also loading some views from XIBs but I use this handy helper category:
@implementation UIView (Initialization)
+ (instancetype)instantiateFromNib {
return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:nil options:nil] firstObject];
}
@end
I didn't want to introduce constraints written in a code so added a overriden viewWillLayoutSubviews
method to my view controller like following:
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
[self.firstView setFrame:self.view.bounds];
[self.secondView setFrame:self.view.bounds];
}
In my case firstView
and secondView
are just an overlay to the whole view controller.
Upvotes: 0
Reputation: 2521
You need to uncheck 'Use size classes' in your xib
and the view frame size will be the one you set and not 600x600
Upvotes: 10
Reputation: 13766
Please refer to this.
header.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:header];
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:header attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0];
[self.view addConstraint:widthConstraint];
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:header attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:130.0];
[self.view addConstraint:widthConstraint];
[self.view addConstraint:heightConstraint];
Upvotes: 3