简体   繁体   中英

Can we load an XIB with auto layout as a subview of a view created programmatically without auto layout and have the subview resize with parent view?

Background:

  • Just started with learning and using auto layout. So I might be going wrong with constraints.
  • Supporting both iOS7 and iOS8, so haven't ventured into size classes.

Scenario: I have a superview created programmatically which is present in all the screens of the app. Now I tried loading an XIB and assigned it as a subview to this superview. It looks fine in the iPhone (as the XIB was designed with iPhone dimensions). But in an iPad, using the same XIB, the subview is keeping the iPhone dimensions.

Is there any way this setup will work on an iPad, having the XIB resize to fill the screen without setting up a constraint between the subview and the superview?

I will post the existing constraints if you think it will help.

You can achieve it by either setting the frame of subview while adding it or adding constraints to subview programmatically.

Enjoy.. :)

you should add constraints for your view from xib after you create it programmatically. Think about it as a usual subview of your main view. so

  1. Create your view from xib

    UIView *someView = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([YOUR_VIEW_CLASS_NAME class]) owner:self options:nil] lastObject];

  2. Add it as subview

    [yourSuperview addSubview: someView];

  3. Add constraints for top, bottom, left, right

NSDictionary *views = @{@"someView":self.background};

[yourSuperview addConstraints:[NSLayoutConstraint
                      constraintsWithVisualFormat:@"H:|[someView]|"
                      options:0
                      metrics:nil
                      views:views]];

[yourSuperview addConstraints:[NSLayoutConstraint
                      constraintsWithVisualFormat:@"V:|[someView]|"
                      options:0
                      metrics:nil
                      views:views]];
  1. Call update via [someView setNeedsLayout];

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