如果设置了锚点,如何获取视图的高度

kbu*_*rjo 1 ios swift nslayoutanchor

我目前正在尝试访问先前为其设置锚点的视图的高度。因此,例如,我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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

哪里:

let topContainerMultipler: Double = 1 / 7
let imageProfileMultipler: Double = 1 / 5
Run Code Online (Sandbox Code Playgroud)

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

我认为有解决此问题的解决方案,但我一直找不到。

4ba*_*bar 5

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