17

I want to round my right corners, but only works for Left corners

let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: [UIRectCorner.TopLeft, UIRectCorner.TopRight], cornerRadii: CGSizeMake(20.0, 20.0))
let maskLayer = CAShapeLayer()
    maskLayer.path = path.CGPath
    view.layer.mask = maskLayer
    view.layer.masksToBounds = true
Diego Quiroz
  • 191
  • 2
  • 7

3 Answers3

42

The problem is that you're getting the view's bounds before it's been resized for the current device. It's larger than it will be later when it appears on screen, so the right side of your rounded rect is off the right side of the screen.

You need to create path and set maskLayer.path later, after the view has been resized, which means during or after the layout phase of the run loop. So either subclass the view and do it in the view's layoutSubviews method, or do it in the view controller's viewDidLayoutSubviews method.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
25

Swift 3

It works for me !

override func layoutSubviews() {
    super.layoutSubviews()
    DispatchQueue.main.async {
       self.containerView.roundCorners(corners: [.topRight,.topLeft], radius: 25)
       self.containerView.layer.masksToBounds = true
    }
    self.layoutIfNeeded()
}

You can check the method "roundCorners" here : https://stackoverflow.com/a/41217863/3687902

Community
  • 1
  • 1
matt
  • 607
  • 7
  • 20
  • This is precisely the logic for a UITableViewCell. Thank you so much. None of the other methods I tried worked. – tuttu47 May 12 '17 at 09:09
1

If you are tried to set the RoundingCorners for View which are design on Storyboard OR Xib then please set the corner and MaskLayer.path into below method.

override func viewDidLayoutSubviews() {
// here you can write the code...
    }
Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
Kiran K
  • 919
  • 10
  • 17