简体   繁体   English

我们可以加载具有自动布局的 XIB 作为以编程方式创建的视图的子视图,而无需自动布局,并使用父视图调整子视图的大小吗?

[英]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.支持 iOS7 和 iOS8,所以还没有涉足大小类。

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.现在我尝试加载一个 XIB 并将其作为子视图分配给这个超级视图。 It looks fine in the iPhone (as the XIB was designed with iPhone dimensions).它在 iPhone 中看起来不错(因为 XIB 是按照 iPhone 尺寸设计的)。 But in an iPad, using the same XIB, the subview is keeping the iPhone dimensions.但是在 iPad 中,使用相同的 XIB,子视图保持 iPhone 尺寸。

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?这个设置有什么办法可以在 iPad 上工作,让 XIB 调整大小以填充屏幕而不在子视图和超级视图之间设置约束?

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.在以编程方式创建视图后,您应该从 xib 为视图添加约束。 Think about it as a usual subview of your main view.将其视为主视图的常规子视图。 so所以

  1. Create your view from xib从 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];通过[someView setNeedsLayout];调用更新[someView setNeedsLayout];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM