设置角半径隐藏UIView

时间:2017-05-03 16:25:49

标签: ios swift uiview rounded-corners

我已创建此扩展程序,可以快速为任何UIView添加圆角:

extension UIView {
    func setCorners(corners: UIRectCorner, radius: CGFloat) {
        print(self.frame) //-> (359.0, 0.0, 306.0, 37.0)
        let maskPath = UIBezierPath(roundedRect: self.frame, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: 0.0))
        let maskLayer = CAShapeLayer()
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
        print(self.frame) //-> (359.0, 0.0, 306.0, 37.0)
    }
}

我用来创建视图并绕过角落的代码:

let view = UIView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 100, height: 40))) //I reposition the view later
view.setCorners(corners: [.bottomLeft, .bottomRight], radius: 8)

在评论setCorners(corners:radius:)时,视图会显示,但在其他方式保持隐藏状态。

知道为什么会这样吗?

2 个答案:

答案 0 :(得分:2)

您正在屏蔽错误的视图区域,请尝试以下操作:

let maskPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height), byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: 0.0))

答案 1 :(得分:2)

看来,您需要在UIBezierPath(roundedRect: self.frame, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: 0.0))

中使用self.bounds而不是self.frame