容器的约束问题

时间:2014-11-18 16:50:21

标签: ios nslayoutconstraint uicontainerview

好的我有一个位于另一个视图容器中的视图控制器。

MainView
  View
    Someview
    ContainerView (contains ContainedViewController)
    Otherview

ContainedViewController
   ContainedView (height can get resized during run).
      UILabel (varying height)
      UIView (fixed size, width & height)

这就是事情...... ContainedViewController中的视图需要在运行时调整大小。它包含一个标签(可以根据其中的文本增长)和一个直接在它下面的静态视图,它永远不会改变大小

所以,我对UILabel的高度有一个限制,我在运行时更改它,具体取决于它需要多大。标签和固定视图之间存在垂直约束,以及所有标准"对主要超级视图的约束。

但是,当我跑步时,我得到"无法同时满足约束",然后是约束日志。冲突的约束是我的新UILabel高度,然后是ContainedView的高度。我得到了一个" UIView-Encapsulated-View-Height" ContainedView的问题。

显然," ContainedView"的高度由 MainView ContainerView 的高度决定。

我想要的是,当UILabel的高度发生变化时,ContainedView的高度会发生变化,然后传播回容器,一直到MainView。但我似乎无法让它发挥作用。

如何在更改标签大小时获取superview及其容器视图以进行调整大小?

1 个答案:

答案 0 :(得分:0)

在主视图控制器中,声明以下覆盖:

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    // Layout the container's content and get its resulting size
    [self.containedViewController.view layoutIfNeeded];
    CGSize containedViewSize = [self.containedViewController contentSize];
    // Now, use containedViewSize to set constraints on the view controller.
    self.containerHeightConstraint.constant = containedViewSize.height;
    self.containerWidthConstraint.constant = containedViewHeight.width;
}

然后,在包含的视图控制器中,声明以下属性:

@property (nonatomic, weak) IBOutlet UIView * contentView;
@property (nonatomic, weak) UIViewController * mainViewController;

在storyboard中,使contentView成为包含视图控制器主视图的子视图。将其限制在主视图的左上角。在contentView中放置您想要的任何内容,包括确定contentView大小的约束。 (不要将contentView的长度和宽度固定到主视图;这将导致您在上面描述的冲突约束。)

在准备设置容器视图控制器的embed segue时,应该设置mainViewController。

这个方法:

- (CGSize)contentSize {
    return self.contentView.frame.size;
}

现在,每当您在容器视图控制器中执行影响contentView大小的操作时,请进行以下调用:

[self.mainViewController.view setNeedsLayout];

对不起,这并不简单,但这是迄今为止我遇到的最佳解决方案。