嗨,我正在寻找一种干净的解决方案,而无需覆盖drawRect或类似的东西来创建一个UIView,在的顶部带有圆角查看。我的主要问题是,如果 View 的大小被调整或类似的事情,将创建变量解决方案。
有没有干净的解决方案? 苹果在第一个表项上也这样做。做到这一点并不难。

最佳答案

您可以通过在 View 的图层上设置mask来做到这一点:

CAShapeLayer * maskLayer = [CAShapeLayer layer];
maskLayer.path = [UIBezierPath bezierPathWithRoundedRect: self.bounds byRoundingCorners: UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii: (CGSize){10.0, 10.}].CGPath;

self.layer.mask = maskLayer;

重要:应该在 View 的layoutSubviews()方法中执行此操作,因此 View 已从 Storyboard 中调整了大小

在Swift
let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: .TopLeft | .TopRight, cornerRadii: CGSize(width: 10.0, height: 10.0)).CGPath

layer.mask = maskLayer

swift 2.x
let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: UIRectCorner.TopLeft.union(.TopRight), cornerRadii: CGSizeMake(10, 10)).CGPath
layer.mask = maskLayer

swift 3.x
let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 10, height: 10)).cgPath
layer.mask = maskLayer

关于objective-c - 仅在UIView顶部具有圆角,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10316902/

10-11 01:34