宽度约束更新后视图未重绘

View is not redrawing after width constraint update

我有以下情况:UIImageView 的宽度需要在特定事件上增加。当我尝试增加它时,约束在增加但视图没有重绘。

UIImageView 有底部、顶部和左侧约束,一个宽度初始设置为 0。

这是来自调试视图层次结构的图像:

更新宽度代码:

self.view.layoutIfNeeded()
self.progressBarThumbWidthConstraint.constant += 30
self.view.updateConstraintsIfNeeded()

UIView.animate(withDuration: 0.3, animations: {
    self.view.layoutIfNeeded()
})

我自己解决的。 问题是视图的约束和相应的框架已正确更新,但视图的图层不是...解决方案是强制图层使用 .setNeedsDisplay()

重绘自身

我花了 4 个多小时来寻找这个愚蠢问题的解决方案...

如果您在子classes UIView 的视图中遇到相同的问题并且此视图具有自定义子图层,您可以确保在视图的框架更改时更新所有子图层(由于某些约束更新或任何其他原因)通过覆盖视图 class 中的 layoutSublayers(of:CALayer) 函数,如下所示:

override func layoutSublayers(of layer: CALayer) {
    if layer == self.layer {
        layer.sublayers?.forEach {
            // By disabling actions we make sure that
            // frame changes for sublayers are applied immediately without animation
            CATransaction.begin()
            CATransaction.setDisableActions(true)
            [=10=].frame = layer.bounds
            CATransaction.commit()
        }
    }
}

我们还通过使用 CATransaction

确保立即应用层更新,没有任何动画或延迟