2016-07-25 153 views
0

我試圖爲uilabel添加邊框,但我只想要頂部,右側和底部邊框。UILabel底部和右邊界

像這樣:

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

我試圖使用這些代碼,但它在默認情況下

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

它不是「默認」,那這段代碼的功能,它永遠不會改變。它在整個元素周圍添加一個邊框。實現你想要的東西在網上有很好的文檔記錄,並且在stackoverflow上有很多問題,你在問一個問題之前是否做過任何研究或搜索? –

回答

0

增加了所有4個方面創建的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() 
} 
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)