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

像这样:

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


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

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

最佳答案

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

10-07 19:49