How to set cornerRadius for only top-left and top-right corner of a UIView?

后端 未结 26 2957
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 06:14

Is there a way to set cornerRadius for only top-left and top-right corner of a UIView?

I tried the following, but it end up not seeing the

26条回答
  •  旧巷少年郎
    2020-11-22 07:06

    In Swift 4.1 and Xcode 9.4.1

    In iOS 11 this single line is enough:

    detailsSubView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]//Set your view here
    

    See the complete code:

    //In viewDidLoad
    if #available(iOS 11.0, *) {
            detailsSubView.clipsToBounds = false
            detailsSubView.layer.cornerRadius = 10
            detailsSubView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
    } else {
          //For lower versions
    }
    

    But for lower versions

    let rectShape = CAShapeLayer()
        rectShape.bounds = detailsSubView.frame
        rectShape.position = detailsSubView.center
        rectShape.path = UIBezierPath(roundedRect: detailsSubView.bounds,    byRoundingCorners: [.topLeft , .topRight], cornerRadii: CGSize(width: 20, height: 20)).cgPath
        detailsSubView.layer.mask = rectShape
    

    Complete code is.

    if #available(iOS 11.0, *) {
        detailsSubView.clipsToBounds = false
        detailsSubView.layer.cornerRadius = 10
        detailsSubView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
    } else {
        let rectShape = CAShapeLayer()
        rectShape.bounds = detailsSubView.frame
        rectShape.position = detailsSubView.center
        rectShape.path = UIBezierPath(roundedRect: detailsSubView.bounds,    byRoundingCorners: [.topLeft , .topRight], cornerRadii: CGSize(width: 20, height: 20)).cgPath
        detailsSubView.layer.mask = rectShape
    }
    

    If you are using AutoResizing in storyboard write this code in viewDidLayoutSubviews().

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    
        if #available(iOS 11.0, *) {
            detailsSubView.clipsToBounds = false
            detailsSubView.layer.cornerRadius = 10
            detailsSubView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        } else {
            let rectShape = CAShapeLayer()
            rectShape.bounds = detailsSubView.frame
            rectShape.position = detailsSubView.center
            rectShape.path = UIBezierPath(roundedRect: detailsSubView.bounds,    byRoundingCorners: [.topLeft , .topRight], cornerRadii: CGSize(width: 20, height: 20)).cgPath
            detailsSubView.layer.mask = rectShape
        }
    }
    

提交回复
热议问题