的UILabel - 在圆角自定义边框左,上,右

问题描述 投票:0回答:1

我期待在加入左上边框和右上的UILabels。什么可行的解决方案是最好的?

rounded tabs uilabels

我努力了 :

func draw(_ rect: CGRect) {

        let cgContext = UIGraphicsGetCurrentContext()
        cgContext?.move(to: CGPoint(x: rect.minX, y: rect.minY))
        cgContext?.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
        cgContext?.setStrokeColor(UIColor.red.cgColor)
        cgContext?.setLineWidth(2.0)
        cgContext?.strokePath()
    }

    func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
        let border = CALayer()

        switch edge {
        case .top:
        border.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: thickness)
        case .left:
        border.frame = CGRect(x:0, y: self.frame.height - thickness, width: self.frame.width, height: thickness)
        case .bottom:
        border.frame = CGRect(x: 0, y: 0, width: thickness, height: self.frame.height)
        case .right:
        border.frame = CGRect(x: self.frame.width - thickness, y: 0, width: thickness, height: self.frame.height)
        default: break
        }

        border.backgroundColor = color.cgColor

        self.addSublayer(border)
    }

    func addBorder2(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
        let border = CALayer()
        border.backgroundColor = color.cgColor

        //top
        border.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 2)

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

        //right
        border.frame = CGRect(x: self.frame.width - thickness, y: 0, width: thickness, height: 2)

        self.addSublayer(border)
        /* SWITCH CASE NOT WORKING !!!
        switch edge {
            case .top:
                border.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 2)
            case .bottom:
                border.frame = CGRect(x: 0, y: self.frame.height - thickness, width: self.frame.width, height:2)
            case .left:
                border.frame = CGRect(x: 0, y: 0, width: thickness, height: 2)
            case .right:
                border.frame = CGRect(x: self.frame.width - thickness, y: 0, width: thickness, height: 2)
            default: break
            }
        */
    }

最终的结果应该是这样的下面:围绕左上角和右上角需要一个边界。底部依然采用无边框。

final result expected

swift border calayer layer radius
1个回答
0
投票

您可以使用UIView设置圆任何UIBezierPath的角落。

setRoundness(ToCorners: [.topLeft, .bottomLeft], for: yourView, withRadius: customRadius)

功能:

func setRoundness(ToCorners corners: UIRectCorner, for view: UIView, withRadius radius: CGFloat) {

    let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
    let mask = CAShapeLayer()
    mask.path = path.cgPath
    view.layer.mask = mask
}
© www.soinside.com 2019 - 2024. All rights reserved.