美文网首页swift
[swift4.2] iOS给UIButton、UILabel添

[swift4.2] iOS给UIButton、UILabel添

作者: 亡鱼 | 来源:发表于2019-03-20 10:37 被阅读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()
        }
    }
    

    相关文章

      网友评论

        本文标题:[swift4.2] iOS给UIButton、UILabel添

        本文链接:https://www.haomeiwen.com/subject/rezamqtx.html