简体   繁体   中英

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: 在此处输入图片说明

self.layer.masksToBounds = true make the border cropped.

You have to use two views one inside another to solve this problem. Also set the frame identical for both of the views.

In child view use

childView.roundCorners(.allCorners, radius: 20)

In parent view use

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

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.

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