Search code examples
iosswiftxcodeuilabelsubclass

Setting custom border using sublass of UILabel in swift


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.


Solution

  • 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.

    enter image description here

    output:

    enter image description here