首页 > 解决方案 > 不同 UIStackView 的子视图之间的等高约束

问题描述

我有一个约束场景,当通过界面构建​​器构建时它可以完美运行,但我无法通过代码实现它。画面布局如下:

在此处输入图像描述

UIStackView具有多个垂直内联的水平UIStackView。这些vertical 中的每一个UIStackView都有多个UIView'。我想要实现的是:inline UIView with equal height

在此处输入图像描述

通过界面生成器创建此类约束时,它可以完美运行:

在此处输入图像描述

但是当通过代码创建这个约束时,我遇到了以下错误:

'Unable to activate constraint with anchors <NSLayoutDimension:0x600002b9a6c0 "UIView:0x7f9e6f075c30.height"> and <NSLayoutDimension:0x600002b9a700 "UIView:0x7f9e6c423d50.height"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'

我尝试使用以下方式创建这些约束:

1.

let heightConstraint = NSLayoutConstraint(item: view1,
                                          attribute: .height,
                                          relatedBy: .equal,
                                          toItem: view2,
                                          attribute: .height,
                                          multiplier: 1,
                                          constant: 0)
NSLayoutConstraint.activate([heightConstraint])

2.

let heightConstraint = NSLayoutConstraint(item: view1,
                                          attribute: .height,
                                          relatedBy: .equal,
                                          toItem: view2,
                                          attribute: .height,
                                          multiplier: 1,
                                          constant: 0)
horizontalStackView.addConstraint(heightConstraint)

存放horizontalStackView所有垂直堆栈视图的水平堆栈视图在哪里。

我无法弄清楚这些约束是在哪里添加的,以便通过界面生成器通过代码创建它们。

标签: iosswiftnslayoutconstraint

解决方案


你应该关注“因为他们没有共同的祖先”部分。该问题可能与您的视图未添加到同一个容器视图有关。

我不知道你是如何创建你的视图的,但在某个时候你需要做一些类似的事情self.addSubview(yourView),这将解决你的问题。


推荐阅读