简体   繁体   中英

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?

I read this post a while ago:

Just two rounded corners?

and also this follow-up post:

Round two corners in UIView

I think these should answer your question.

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
}

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;

Objective C

iOS 11 using view corner radius

if (@available(iOS 11.0, *)) {
            _parentView.clipsToBounds = YES;
            _parentView.layer.cornerRadius = 20;
            _parentView.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
        } else {
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_parentView.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(20.0, 20.0)];

            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = _parentView.bounds;
            maskLayer.path  = maskPath.CGPath;
            _parentView.layer.mask = maskLayer;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM