将圆角应用于 UIView 时约束无法正确显示(仅适用于 iPhone XS Max 和 + 版本)

Constraints not showing properly when applying rounded corners to UIView (only on iPhone XS Max & +Versions)

我正在使用此函数对 UIView 进行舍入:

func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
    }

override func viewDidLoad() {
        super.viewDidLoad()

        someUIView.roundCorners([.topLeft,.topRight], radius: 20)            
    }

这按预期工作,但在 iPhone XS Max 和 All Plus 模型上测试时,约束变得混乱,但只在屏幕左侧。

我不明白为什么,我认为这与圆角功能如何在视图上应用图层有关,因为当我删除圆角布局时即使在那些 iPhone 模型上也很好,或者它可能与边距有关? Idk,但如果有人可以帮助我解决这个问题,我将不胜感激。

Image so you can appreciate the problem (XS, XSMax, 7, 7+)

您正在 UIBezierPath 使用 self.bounds 视图布局之前设置。

将此添加到您的自定义 UIView class:

override func layoutSubviews() {
     super.layoutSubviews()
     self.roundCorners([.topLeft,.topRight], radius: 20)
}

并从视图控制器的 viewDidLoad() 函数中删除调用。