skip to Main Content

This is my convenience init for UIButton:

convenience init(underlinedTitle: String, font: UIFont, color: UIColor) {
    var configuration = UIButton.Configuration.plain()
    configuration.title = underlinedTitle
    configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
        var outgoing = incoming
        outgoing.font = font
        outgoing.foregroundColor = color
        outgoing.underlineStyle = .single
        outgoing.underlineColor = color
        return outgoing
    }
    self.init(configuration: configuration)
}

and the effect is following:

enter image description here

Why is it not underlined?

2

Answers


  1. try use way from this answer
    https://stackoverflow.com/a/41166179/11335258

    @IBOutlet weak var yourButton: UIButton!
    
    var attrs = [
    NSFontAttributeName : UIFont.systemFontOfSize(19.0),
    NSForegroundColorAttributeName : UIColor.redColor(),
    NSUnderlineStyleAttributeName : 1]
    
    var attributedString = NSMutableAttributedString(string:"")
    
    override func viewDidLoad() {
      super.viewDidLoad()
    
      let buttonTitleStr = NSMutableAttributedString(string:"My Button", attributes:attrs)
      attributedString.appendAttributedString(buttonTitleStr)
      yourButton.setAttributedTitle(attributedString, forState: .Normal)
    }
    
    Login or Signup to reply.
  2. Hmm… can’t find this documented anywhere, but appears to be correct.

    To add underline style:

    outgoing.underlineStyle = [.single]
    

    To remove underline style:

    outgoing.underlineStyle = []
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search