UILabel的右下边框

时间:2016-07-25 08:31:10

标签: ios swift uilabel border

我尝试为uilabel添加边框,但我只想要有顶部,右边和底部边框。

像这样:

                      |
        I am a label  |
                      |
       ----------------

我尝试使用这些代码,但默认情况下会添加所有4个边

myLabel.layer.borderWidth = 1;
myLabel.layer.borderColor = UIColorCode.init(hexString: "#666666")

2 个答案:

答案 0 :(得分:0)

创建UILabel的子类并添加以下代码。这将根据您的需要绘制边框。

 override func drawRect(rect: CGRect) {

        let outerBorder = UIColor.blackColor()
        let lineWidth : CGFloat = 2.0
        let insetRect = rect.insetBy(dx: lineWidth/2, dy: lineWidth/2)
        let startingTopPoint   = CGPointMake(insetRect.origin.x,insetRect.origin.y)
        let endingTopPoint  = CGPoint(x: insetRect.maxX, y: insetRect.minY)

        let bottomLeft   = CGPoint(x: insetRect.minX, y: insetRect.maxY)
        let bottomRight     = CGPoint(x: insetRect.maxX, y: insetRect.maxY)


        let path = UIBezierPath()
        path.moveToPoint(startingTopPoint)
        path.addLineToPoint(endingTopPoint)
        path.lineWidth = 2.0
        path.addLineToPoint(bottomRight)
        path.addLineToPoint(bottomLeft)


        outerBorder.setStroke()
        path.stroke()
}

答案 1 :(得分:0)

let borderWidth: CGFloat = 1.0

let borderLayer = CAShapeLayer()
borderLayer.lineWidth = borderWidth
borderLayer.fillColor = UIColor.clearColor().CGColor
borderLayer.strokeColor = UIColor.blueColor().CGColor

let borderLine = UIBezierPath()
borderLine.moveToPoint(CGPoint(x: 0, y: myLabel.bounds.height - borderWidth / 2))
borderLine.addLineToPoint(CGPoint(x: myLabel.bounds.width - borderWidth / 2, y: myLabel.bounds.height - borderWidth / 2))
borderLine.addLineToPoint(CGPoint(x: myLabel.bounds.width - borderWidth / 2, y: 0))

borderLayer.path = borderLine.CGPath

myLabel.layer.addSublayer(borderLayer)