mariusLAN mariusLAN - 4 months ago 37
Objective-C Question

Rounded Corners only on Top of a UIView

Hi i am searching a clean solution without overwriting

drawRect
or stuff like that to create a
UIView
with Rounded corners on the Top of the View. My main problem here is to create variable solution if the view is getting resized or something like that.
Is there a clean solution? Apple is this doing too on the first table item. it can't be so hard to do this.

Answer

You can do this by setting a mask on your view's layer:

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

self.layer.mask = maskLayer;

You should do this in your view controller's viewDidLayoutSubviews method, so the view has already been resized from the storyboard


In Swift <= 1.2

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: bounds, byRoundingCorners: UIRectCorner.topLeft.union(.topRight), cornerRadii: CGSize(width: 10, height: 10)).cgPath
layer.mask = maskLayer
Comments