Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you make a UIView with rounded top corners and square bottom corners

I am trying to get a view with rounded top corners and square bottom corners, similar to the top row of a grouped UITableViewCell.

Anyone one know an easy way to draw it and not use a background image?

like image 712
joels Avatar asked Jun 27 '11 22:06

joels


2 Answers

With iOS 11 there is a new structure introduced named CACornerMask.

With this structure you can make changes with corners: topleft, topright, bottom left, bottom right.

Swift Sample:

myView.clipsToBounds = true
myView.layer.cornerRadius = 10
myView.layer.maskedCorners = [.layerMinXMinYCorner,.layerMaxXMinYCorner]

Objective-C Sample

self.view.clipsToBounds = YES;
self.view.layer.cornerRadius = 10;
self.view.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
like image 181
abdullahselek Avatar answered Sep 21 '22 23:09

abdullahselek


Swift 4: For iOS 11 onwards

override func viewDidLoad() {
    super.viewDidLoad()

    if #available(iOS 11.0, *) {
        self.viewToRound.clipsToBounds = true
        viewToRound.layer.cornerRadius = 20
        viewToRound.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
    } else {
        // Fallback on earlier versions
    }
}

Earlier iOS Versions

override func viewDidLayoutSubviews() {
    self.viewToRound.clipsToBounds = true
    let path = UIBezierPath(roundedRect: viewToRound.bounds,
                            byRoundingCorners: [.topRight, .topLeft],
                            cornerRadii: CGSize(width: 20, height: 20))

    let maskLayer = CAShapeLayer()

    maskLayer.path = path.cgPath
    viewToRound.layer.mask = maskLayer
}
like image 44
Naishta Avatar answered Sep 21 '22 23:09

Naishta