【问题标题】:constraints problems with containers容器的约束问题
【发布时间】:2014-11-18 16:50:20
【问题描述】:

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

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 的高度。 ContainedView 出现“UIView-Encapsulated-View-Height”问题。

显然,“ContainedView”的高度是由 MainViewContainerView 的高度决定的。

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

如何获取超级视图,以及在更改标签大小时调整大小的容器视图?

【问题讨论】:

    标签: ios nslayoutconstraint uicontainerview


    【解决方案1】:

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

    - (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;
    

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

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

    还有这个方法:

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

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

    [self.mainViewController.view setNeedsLayout];
    

    抱歉,这并不简单,但这是迄今为止我找到的解决此问题的最佳解决方案。

    【讨论】:

      猜你喜欢
      • 2011-02-12
      • 1970-01-01
      • 2011-07-06
      • 2020-11-18
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多