Reputation: 316
I have created a subclass of UILabel for custom bottom border. The subclass is: import UIKit
class BottomBorderClass: UILabel {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.setBottomBorder()
}
override init(frame: CGRect) {
super.init(frame:frame)
self.setBottomBorder()
}
func setBottomBorder()
{
self.text = "TITLE LABEL"
self.textColor = UIColor.grayColor()
let layer:CALayer = self.layer
let bottomBorder:CALayer = CALayer.init(layer: layer)
bottomBorder.borderColor = UIColor.whiteColor().CGColor
bottomBorder.borderWidth = 2;
bottomBorder.frame = CGRectMake(-1, self.layer.frame.size.height-1,
self.layer.frame.size.width, 2);
bottomBorder.borderColor = UIColor.whiteColor().CGColor
self.layer.addSublayer(bottomBorder)
}
}
In view controller i am calling the class on @IBOutlet weak var someLabel:BottomBorderClass
The problem is the border and text is not getting displayed. Please help!! Thanks in Advance.
Upvotes: 2
Views: 2047
Reputation: 712
You can create an extension for CALayer
import Foundation
import UIKit
extension CALayer {
func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
let border = CALayer()
switch edge {
case UIRectEdge.top:
border.frame = CGRect.zero
border.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: thickness)
break
case UIRectEdge.bottom:
border.frame = CGRect(x: 0, y: self.bounds.height - thickness, width: self.bounds.width, height: thickness)
break
case UIRectEdge.left:
border.frame = CGRect(x: 0, y: 0, width: thickness, height: self.bounds.height)
break
case UIRectEdge.right:
border.frame = CGRect(x: self.bounds.width - thickness, y: 0, width: thickness, height: self.bounds.height)
break
default:
break
}
border.backgroundColor = color.cgColor;
self.addSublayer(border)
}
}
and in your controller, for exemple :
@IBOutlet weak var someLabel: UILabel !
someLabel.layer.addBorder(edge: UIRectEdge.bottom, color: UIColor.red, thickness: 2)
with this method you can use addBorder function with any UILabel, UIButton, ...
Upvotes: 0
Reputation: 2149
Change your function like this.
func setBottomBorder(){
let borderWidth:CGFloat = 4.0 //Change this according to your needs
let lineView = UIView.init(frame: CGRect.init(x: 0, y:self.frame.size.height - borderWidth , width: self.frame.size.width, height: borderWidth))
lineView.backgroundColor = UIColor.green
self.addSubview(lineView)
}
From your attribute inspector, don't forget to change class like this.
output:
Upvotes: 3