开发者

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

开发者 https://www.devze.com 2023-03-15 23:43 出处:网络
I am trying to get a view with rounded top corners and square bottom corners, similar to the top row of a grouped UITableViewCell.

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 dr开发者_运维知识库aw 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;
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消