Underlining text in UIButton

后端 未结 18 1860
终归单人心
终归单人心 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:12

    The Swift 5.0 version that works as of September 2019 in Xcode 10.3:

    extension UIButton {
      func underlineText() {
        guard let title = title(for: .normal) else { return }
    
        let titleString = NSMutableAttributedString(string: title)
        titleString.addAttribute(
          .underlineStyle,
          value: NSUnderlineStyle.single.rawValue,
          range: NSRange(location: 0, length: title.count)
        )
        setAttributedTitle(titleString, for: .normal)
      }
    }
    

    To use it, set your button title first with button.setTitle("Button Title", for: .normal) and then call button.underlineText() to make that title underlined.

提交回复
热议问题