基本效果
// 给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()
}
}