在swift中使用UILabel的子类设置自定义边框

问题描述:

我已经为自定义底部边界创建了UILabel的子类。子类是: 进口的UIKit在swift中使用UILabel的子类设置自定义边框

类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) 

} 

}

在视图控制器我呼吁@IBOutlet弱VAR someLabel类:BottomBorderClass

问题是边框,文字没有显示。请帮忙!!提前致谢。

+0

你用IBDesignable的BottomBorderClass? –

+1

如果您正在使用故事板:您是否在Identity Insprector中设置了“自定义类”? – niggeulimann

+1

检查我的答案。如果有帮助,请不要忘记点击向上箭头并检查标志。 :) –

像这样改变你的功能。

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) 

} 

从你的属性检查器,不要忘记改变这样的类。

enter image description here

输出:

enter image description here

+0

谢谢你。我只是错过了一步,我已经在评论部分更新了它。 – BlackPearl12

+0

希望你upvote并接受我的答案。 –

您可以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) 
    } 
} 

,并在控制器中创建一个扩展,用于为例:

@IBOutlet weak var someLabel: UILabel ! 
someLabel.layer.addBorder(edge: UIRectEdge.bottom, color: UIColor.red, thickness: 2) 

用这种方法你可以使用addBorder功能与任何的UILabel,UIButton的,...