简体   繁体   中英

UILabel bottom and right border

I tried to add border for a uilabel , but I only want to have top, right, and bottom border.

Like this:

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

I tried to use these codes, but it adds all 4 sides by default

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

Create a subclass of UILabel and add the following code. This will draw borders as you need.

 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()
}
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)

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