Underlining text in UIButton

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

    Here is my function, works in Swift 1.2.

    func underlineButton(button : UIButton, text: String) {
    
        var titleString : NSMutableAttributedString = NSMutableAttributedString(string: text)
        titleString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleSingle.rawValue, range: NSMakeRange(0, count(text.utf8)))
        button.setAttributedTitle(titleString, forState: .Normal)
    }
    

    UPDATE Swift 3.0 extension:

    extension UIButton {
        func underlineButton(text: String) {
            let titleString = NSMutableAttributedString(string: text)
            titleString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0, text.characters.count))
            self.setAttributedTitle(titleString, for: .normal)
        }
    }
    

提交回复
热议问题