为什么在为子视图添加图层蒙版时需要调用 layoutIfNeeded()?

Why do I need to call layoutIfNeeded() when adding a layer mask to a subview?

我的主视图有一个子视图,我使用以下扩展添加了一个掩码:

extension UIView{
func addTopRoundCorners(){
    let bezierPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [UIRectCorner.topLeft, UIRectCorner.topRight], cornerRadii: CGSize(width: 20, height: 20))
    let maskLayer = CAShapeLayer()
    maskLayer.path = bezierPath.cgPath
    maskLayer.fillColor = UIColor.red.cgColor
    self.layer.mask = maskLayer
}

}

我注意到如果我在将掩码添加到我的子视图之前在我的主视图上调用 layoutIfNeeded(),则此代码对我的子视图的影响只会出现在屏幕上。如果有人能向我解释这是为什么,我将不胜感激?

layoutIfNeeded 将计算您的视图的位置和大小。如果在计算最终位置和大小之前调用 addTopRoundCorners() 函数,则用于创建 UIBezierPathself.bounds 将是错误的。

自动布局不会自动调整遮罩层的大小,也不会调用 addTopRoundCorners 重新创建路径。