2

我目前正在尝试访问我之前为其设置锚点的视图的高度。因此,例如,我searchTable在 ViewController 中设置了使用以下内容的左、右、上和下锚:

searchTable.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
searchTable.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
searchTable.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
searchTable.bottomAnchor.constraint(equalTo: menuBar.topAnchor).isActive = true

searchTable是我创建的一个类的对象,它继承自 UIView 并在其中有一个 UIImageView。我通过在 init 函数中使用以下内容来约束 UIImageView:

imageView.topAnchor.constraint(equalTo: topContainer.topAnchor, constant: 10).isActive = true
imageView.leftAnchor.constraint(equalTo: topContainer.leftAnchor, constant: 10).isActive = true
imageView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: topContainerMultiplier * imageProfileMultiplier).isActive = true
imageView.widthAnchor.constraint(equalTo: self.heightAnchor, multiplier: topContainerMultiplier * imageProfileMultiplier).isActive = true

在哪里:

let topContainerMultipler: Double = 1 / 7
let imageProfileMultipler: Double = 1 / 5

在 init 的 init 函数中searchTable,我尝试将角半径设置为图像大小的一半。我尝试使用self.frame.height,self.frame.size.heightself.bounds.height获取约束的.constant值,但都返回 0。self.heightAnchor

我认为有一个解决方案来解决这个问题,但我一直无法找到它。

4

2 回答 2

8

在定义约束之后,您正在查询视图框架的高度,但在布局实际上将这些约束解析为框架矩形之前。一种方法是调用layoutIfNeeded强制布局立即发生,然后使用view.frame.size.height. init 方法可能不是执行此操作的合适位置,而不是viewDidLoad在控制器内部。或者,您可以在viewDidLayoutSubviews每次更新视图布局时重新计算角半径(在这种情况下,您不需要layoutIfNeeded)。

于 2017-10-03T08:24:03.933 回答
0

如果您已经使用了顶部、底部、前导和尾随,请不要使用高度约束。

尝试通过添加背景颜色或使用调试视图层次结构按钮来直观地调试视图。

要获得视图的高度,您应该使用view.frame.size.height

编辑(OP 问题已编辑)

您的问题是您尝试在对象高度刚刚初始化但尚未显示时访问它。您应该创建一个更新 UI 的函数,并在加载视图后调用它。

于 2017-10-03T07:50:53.990 回答