swift

[swift4.2] iOS给UIButton、UILabel添

2019-03-20  本文已影响0人  亡鱼

基本效果


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()
    }
}
上一篇 下一篇

猜你喜欢

热点阅读