Search code examples
iosswiftborderrounded-corners

Borders are cropped with rounded corners? Swift


I've seen a few questions on this subject, but they are only answers one of the problems. I'm rounding corners from one side by:

func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
    let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
    let mask = CAShapeLayer()
    mask.path = path.cgPath
    self.layer.masksToBounds = true
    self.layer.mask = mask
}

and implementation:

detailsView.roundCorners(.allCorners, radius: 20)

Then, I'm trying to add borders by:

func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {

    let border = CALayer()

    switch edge {
        case UIRectEdge.top:
            border.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness)

        case UIRectEdge.bottom:
            border.frame = CGRect(x:0, y: frame.height - thickness, width: frame.width, height:thickness)

        case UIRectEdge.left:
            border.frame = CGRect(x:0, y:0, width: thickness, height: frame.height)

        case UIRectEdge.right:
            border.frame = CGRect(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)

        default: do {}
    }

    border.backgroundColor = color.cgColor
    addSublayer(border)
}

and implementation:

detailsView.layer.addBorder(edge: .top, color: .lightLavender, thickness: 1)

What am I doing wrong? I get this result – borders are cropped: enter image description here


Solution

  • I've rounded top corners by:

    func roundCorners(radius: CGFloat, mask: CACornerMask) {
        cornerRadius = radius
        maskedCorners = mask
    

    Implementation:

        detailsView.layer.roundCorners(radius: 20, mask: [.layerMinXMinYCorner, .layerMaxXMinYCorner])
    

    Borders:

    extension UIView {
    @IBInspectable var borderWidthV: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }
    
    @IBInspectable var borderColorV: UIColor? {
        get {
            return UIColor(cgColor: layer.borderColor!)
        }
        set {
            layer.borderColor = newValue?.cgColor
        }
      }
    }
    

    And after that, I've just added white UIView to the bottom of my view to hide bottom borders.