Underlining text in UIButton

后端 未结 18 1897
终归单人心
终归单人心 2020-11-29 15:56

Can anyone suggest how to underline the title of a UIButton ? I have a UIButton of Custom type, and I want the Title to be underlined, but the Interface Builder does not pr

18条回答
  •  悲哀的现实
    2020-11-29 16:17

    Swift 3 version for @NickH247's answer with custom underline color, linewidth and gap:

    import Foundation
    
    class UnderlinedButton: UIButton {
    
        private let underlineColor: UIColor
        private let thickness: CGFloat
        private let gap: CGFloat
    
        init(underlineColor: UIColor, thickness: CGFloat, gap: CGFloat, frame: CGRect? = nil) {
            self.underlineColor = underlineColor
            self.thickness = thickness
            self.gap = gap
            super.init(frame: frame ?? .zero)
        }
    
        override func draw(_ rect: CGRect) {
            super.draw(rect)
    
            guard let textRect = titleLabel?.frame,
                let decender = titleLabel?.font.descender,
                let context = UIGraphicsGetCurrentContext() else { return }
    
            context.setStrokeColor(underlineColor.cgColor)
            context.move(to: CGPoint(x: textRect.origin.x, y: textRect.origin.y + textRect.height + decender + gap))
            context.setLineWidth(thickness)
            context.addLine(to: CGPoint(x: textRect.origin.x + textRect.width, y: textRect.origin.y + textRect.height + decender + gap))
            context.closePath()
            context.drawPath(using: .stroke)
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    

提交回复
热议问题