LinusG.
LinusG.

Reputation: 28892

Setting corner radius hides UIView

I've created this extension to quickly add rounded corners to any 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)
    }
}

The code I use to create the view and round its corners:

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)

When commenting out the setCorners(corners:radius:), the view appears, while it stays hidden otherwise.

Any idea why this is happening?

Upvotes: 1

Views: 902

Answers (2)

aknew
aknew

Reputation: 1121

It seems, that you need use self.bounds instead self.frame in UIBezierPath(roundedRect: self.frame, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: 0.0))

Upvotes: 2

Gigi
Gigi

Reputation: 636

You are masking a wrong view area, try this:

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))

Upvotes: 2

Related Questions