[swift4.2] iOS给UIButton、UILabel添加下划线(以绘制下划线的方式)

基本效果


WX20190320-104309.png
// 给button添加下划线 
class BottonLineBtn: UIButton {
    
    var lineColor: UIColor!
    func setColor(color: UIColor) {
        if lineColor == nil {
            lineColor = UIColor.white
        }
        lineColor = color.copy() as? UIColor
        self.setNeedsDisplay()
    }
    
    override func draw(_ rect: CGRect) {
        let textRect: CGRect = self.titleLabel!.frame
        let contextRef: CGContext = UIGraphicsGetCurrentContext()!
        let descender: CGFloat = self.titleLabel!.font.descender
        contextRef.setStrokeColor(lineColor.cgColor)
        contextRef.move(to: CGPoint(x: textRect.origin.x, y: textRect.origin.y + textRect.size.height + descender + 2))
        contextRef.addLine(to: CGPoint(x: textRect.origin.x + textRect.size.width, y: textRect.origin.y + textRect.size.height + descender + 2))
        contextRef.closePath()
        contextRef.strokePath()
    }
    
}

// UILabel同理 添加下划线 
class BottonLineLabel: UILabel {
    
    var lineColor: UIColor!
    func setColor(color: UIColor) {
        if lineColor == nil {
            lineColor = UIColor.white
        }
        lineColor = color.copy() as? UIColor
        self.setNeedsDisplay()
    }
    
    override func draw(_ rect: CGRect) {
        let textRect: CGRect = self.frame
        let contextRef: CGContext = UIGraphicsGetCurrentContext()!
        let descender: CGFloat = self.font.descender
        contextRef.setStrokeColor(lineColor.cgColor)
        contextRef.move(to: CGPoint(x: textRect.origin.x, y: textRect.origin.y + textRect.size.height + descender + 2))
        contextRef.addLine(to: CGPoint(x: textRect.origin.x + textRect.size.width, y: textRect.origin.y + textRect.size.height + descender + 2))
        contextRef.closePath()
        contextRef.strokePath()
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。